<?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 Hajagha Hasanli on Medium]]></title>
        <description><![CDATA[Stories by Hajagha Hasanli on Medium]]></description>
        <link>https://medium.com/@hajaghahasanli?source=rss-d7911bb64fc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DdQVOvgmJUDvnj6oH1bDdQ.jpeg</url>
            <title>Stories by Hajagha Hasanli on Medium</title>
            <link>https://medium.com/@hajaghahasanli?source=rss-d7911bb64fc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:40:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hajaghahasanli/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[Postgres Indexes, Measured: What Each One Does and When It Quietly Stops Working]]></title>
            <link>https://medium.com/@hajaghahasanli/postgres-indexes-measured-what-each-one-does-and-when-it-quietly-stops-working-8da3a0f0e13f?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8da3a0f0e13f</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-11-04T07:01:02.589Z</atom:updated>
            <content:encoded><![CDATA[<h4>B-tree, unique, composite, partial, expression, GIN, GiST and safe production builds, each shown with a real EXPLAIN ANALYZE</h4><p>Most index advice fits on a sticky note: “add an index on the columns in your WHERE clause.” It is not wrong, but it leaves out the part that causes incidents: the index that exists but is not used, the composite index that only works from the left, the CREATE INDEX that freezes writes on a busy table, and the half-built index that slows every insert while helping no query.</p><p>This article walks through the index types you will actually use in PostgreSQL, using a small HR and knowledge-base application as the example. Every section follows the same order:</p><ol><li><strong>The problem:</strong> a real query.</li><li><strong>Without an index:</strong> what Postgres has to do.</li><li><strong>With the right index:</strong> what changes, measured.</li><li><strong>When it stops working:</strong> the conditions that make the planner ignore it.</li></ol><p><strong>Setup for all measurements:</strong> PostgreSQL 16.15 on Linux, a leave_requests table with 100,000 rows (about 8,300 employees, roughly 12 requests each), a pages table with 10,000 documents of which about 3,000 are in the trash, and a small public_holidays table. Timings on your hardware will differ; the page counts and plan shapes are the point.</p><h3>0. How Postgres searches without an index</h3><p>Rows in a table are stored in the order they were written. There is no sorting:</p><pre>row 1: id=1  employee_id=57  start_date=2026-03-02<br>row 2: id=2  employee_id=3   start_date=2026-01-15<br>row 3: id=3  employee_id=57  start_date=2026-11-20<br>...<br>row 100000</pre><p>Ask for one employee’s requests:</p><pre>SELECT * FROM leave_requests WHERE employee_id = 57;</pre><p>With no index, Postgres has one option: read every row and check the condition. That is a <strong>sequential scan</strong>.</p><pre>Seq Scan on leave_requests (actual rows=17 loops=1)<br>  Filter: (employee_id = 57)<br>  Rows Removed by Filter: 99983<br>  Buffers: shared hit=1235<br>Execution Time: 6.782 ms</pre><p>Employee 57 has 17 requests. To find them, Postgres read all 1,235 pages of the table and threw away 99,983 rows. A book without an index works the same way: to find every mention of one word, you turn all 500 pages.</p><h3>1. B-tree: the default, and why it is fast</h3><pre>CREATE INDEX ix_leave_employee ON leave_requests (employee_id);</pre><p>A B-tree keeps the indexed values <strong>sorted</strong> in a tree of pages. Each leaf entry stores a value and the physical location of the row it came from. To find 57, Postgres starts at the root, follows the branch whose range contains 57, and arrives at the leaf that lists every row with that value.</p><pre>Bitmap Heap Scan on leave_requests (actual rows=17 loops=1)<br>  Heap Blocks: exact=17<br>  Buffers: shared hit=17 read=2<br>  -&gt;  Bitmap Index Scan on ix_leave_employee (actual rows=17 loops=1)<br>        Index Cond: (employee_id = 57)<br>        Buffers: shared read=2<br>Execution Time: 0.454 ms</pre><p>Two index pages (the root and one leaf) plus 17 table pages, instead of 1,235 pages. About 15 times faster here, and the gap grows with the table.</p><p>How shallow the tree stays is the part people underestimate. Each page holds hundreds of entries, so every level multiplies capacity by hundreds. I checked the tree height with the pageinspect extension:</p><pre>100,000 rows    -&gt; root + leaf                  (2 page reads)<br>10,000,000 rows -&gt; root + internal + leaf       (3 page reads)</pre><p>A hundred times more data cost one extra page read. That logarithmic growth is the whole reason B-trees are the default.</p><p>Because the values are sorted, a B-tree also serves ranges and ordering:</p><pre>WHERE start_date BETWEEN &#39;2026-03-01&#39; AND &#39;2026-03-31&#39;  -- find the start, then read forward<br>WHERE start_date &gt; &#39;2026-11-01&#39;<br>ORDER BY start_date                                      -- already sorted, no separate sort step</pre><h4>When a B-tree does not help</h4><p><strong>A pattern that starts with a wildcard.</strong> WHERE title LIKE &#39;%report%&#39; can match anywhere in the string. In a sorted list those titles are scattered, so a B-tree cannot narrow the search. (Section 6 solves this.)</p><p><strong>A function applied to the column.</strong> An index on title stores title, not lower(title). A query on lower(title) cannot use it. (Section 5.)</p><p><strong>A prefix search under a natural-language collation.</strong> This one surprises people. LIKE &#39;Annual%&#39; looks like a perfect B-tree query, since all matching titles are adjacent. Yet on my database, which uses the C.UTF-8 collation, a plain index on title was ignored:</p><pre>Seq Scan on pages<br>  Filter: (title ~~ &#39;Annual%&#39;::text)</pre><p>Postgres can only turn a LIKE prefix into an index range when the index uses byte-wise ordering. With linguistic collations, &quot;sorted&quot; follows language rules that do not line up with the pattern. The fix is an operator class built for pattern matching, or a C collation on the index:</p><pre>CREATE INDEX ON pages (title text_pattern_ops);<br>-- or<br>CREATE INDEX ON pages (title COLLATE &quot;C&quot;);</pre><pre>Bitmap Index Scan on ix_pages_title_c<br>  Index Cond: ((title &gt;= &#39;Annual&#39;::text) AND (title &lt; &#39;Annuam&#39;::text))</pre><p>Note the rewritten condition: Postgres converts the prefix into a range from &#39;Annual&#39; up to (but not including) &#39;Annuam&#39;.</p><h3>2. Unique indexes: a rule enforced at the only safe place</h3><p>A public_holidays table must never contain the same date twice. The obvious application code is &quot;check, then insert&quot;:</p><pre>if not db.exists(holiday_date=date):<br>    db.insert(holiday_date=date, name=name)</pre><p>I ran exactly that logic from two sessions at the same time, without a unique index:</p><pre>Session A: SELECT count(*) ... -&gt; 0      Session B: SELECT count(*) ... -&gt; 0<br>Session A: INSERT ... -&gt; OK              Session B: INSERT ... -&gt; OK<br>SELECT * FROM public_holidays WHERE holiday_date = &#39;2026-11-08&#39;;<br>2026-11-08 | Victory Day (B)<br>2026-11-08 | Victory Day (A)</pre><p>Both checks ran before either insert committed, so both saw “no row” and both wrote one. This is a classic <strong>race condition</strong>, and no amount of checking in application code removes it, because the check and the write are two separate steps.</p><p>The fix belongs in the database:</p><pre>CREATE UNIQUE INDEX ux_holiday_date ON public_holidays (holiday_date);</pre><p>(Adding the index after the race failed with Key (holiday_date)=(2026-11-08) is duplicated, which is a useful reminder to clean existing data before adding a constraint.)</p><p>With the unique index in place, I repeated the concurrent inserts. Session A inserted inside an open transaction; session B tried to insert the same date:</p><pre>Session B waited: 1.6 s<br>ERROR:  duplicate key value violates unique constraint &quot;ux_holiday_date&quot;<br>DETAIL:  Key (holiday_date)=(2026-12-25) already exists.</pre><p>Session B did not fail immediately. It <strong>waited</strong> for session A’s transaction to finish, because A might still roll back. Once A committed, B received the error. The application catches this error (SQLSTATE 23505, unique_violation) and turns it into a clear response such as HTTP 409 Conflict.</p><p>A unique index is structurally a normal B-tree. The difference is that every insert also asks the tree “does this key already exist?” before it writes.</p><h3>3. Composite indexes: sorted left to right</h3><pre>CREATE INDEX ix_leave_emp_start ON leave_requests (employee_id, start_date);</pre><p>The index sorts by the first column, and only within equal first values by the second:</p><pre>(3,  2026-01-15)<br>(3,  2026-06-01)<br>(57, 2026-03-02)   &lt;- all of employee 57 is together<br>(57, 2026-11-20)      and sorted by date inside that group<br>(57, 2027-01-05)<br>(72, 2026-02-10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gThVvESL38oF4ti3zldf2w.png" /></figure><p><em>Figure 1. Filtering by employee jumps straight to one group. Filtering only by date finds matches scattered across every group.</em></p><p>Measured on the same data:</p><pre>Query                                              Index pages   Rows   Time<br>employee_id = 57                                   2             17     0.05 ms<br>employee_id = 57 AND start_date &gt; &#39;2025-06-01&#39;     2             5      0.02 ms<br>start_date = &#39;2025-06-01&#39;  (no employee_id)        275           87     1.39 ms</pre><p>The first two queries navigate the tree. The third is the interesting one: Postgres <strong>did</strong> use the composite index, but it could not navigate it, because dates are only sorted inside each employee’s group. It read all 275 pages of the index instead, which was cheaper than the 1,235-page table but a hundred times more work than a real lookup. A query plan that says “Index Scan” is not proof that the index is being used well.</p><p>The same ordering gives you sorted results for free:</p><pre>SELECT * FROM leave_requests WHERE employee_id = 57 ORDER BY start_date DESC LIMIT 5;</pre><pre>Limit<br>  -&gt;  Index Scan Backward using ix_leave_emp_start on leave_requests<br>        Index Cond: (employee_id = 57)</pre><p>There is no sort step. Postgres walks the index backwards and stops after five rows.</p><p><strong>Rules for column order:</strong></p><ul><li>Put columns compared with equality first and the range column last: (employee_id, start_date), not the reverse.</li><li>An index on (a, b) also serves queries on a alone. You rarely need a separate index on a.</li><li>A phone book sorted by “surname, first name” finds “Hasanli, Hajagha” instantly, but cannot find everyone named “Hajagha” without reading the whole book.</li></ul><p><strong>Version note:</strong> PostgreSQL 18 added <strong>skip scan</strong> for B-trees, which lets the planner use a multicolumn index even when the leading column is not filtered, by jumping from one leading value to the next. It helps most when the leading column has few distinct values. With about 8,300 employees, as here, a dedicated index on start_date would still be the better choice.</p><h3>4. Covering indexes: answering from the index alone</h3><p>If a query only needs a few columns, the index can carry them so Postgres never visits the table:</p><pre>CREATE INDEX ix_leave_cover ON leave_requests (employee_id) INCLUDE (start_date, end_date);<br>SELECT start_date, end_date FROM leave_requests WHERE employee_id = 57;</pre><pre>Index Only Scan using ix_leave_cover on leave_requests (actual rows=17 loops=1)<br>  Index Cond: (employee_id = 57)<br>  Heap Fetches: 0<br>  Buffers: shared hit=1 read=3</pre><p>Four pages instead of nineteen. INCLUDE columns are stored in the leaf entries but are not part of the sort order, so they make the index wider without changing how it is searched.</p><p>Heap Fetches: 0 depends on maintenance. Postgres can only skip the table for pages the <strong>visibility map</strong> marks as all-visible, which VACUUM maintains. On a table with heavy, recent writes, an &quot;index-only&quot; scan may still fetch many rows from the table.</p><h3>5. Partial and expression indexes: the query must match the index exactly</h3><p>The knowledge-base search only ever looks at live pages, and it should ignore case. Both requirements can be built into one index:</p><pre>CREATE INDEX ix_pages_lower_live<br>    ON pages (lower(title) text_pattern_ops)<br>    WHERE deleted_at IS NULL;</pre><ul><li><strong>Partial:</strong> the WHERE clause keeps the 3,000 trashed pages out of the index. Here that made it 288 kB instead of 392 kB, and trashing or restoring a page does less index work.</li><li><strong>Expression:</strong> the index stores lower(title), so a case-insensitive comparison can use it.</li></ul><p>The price is precision. The planner uses the index only when it can prove the query asks for the same thing:</p><pre>-- same expression, same condition<br>WHERE lower(title) LIKE &#39;annual%&#39; AND deleted_at IS NULL<br>  -&gt;  Bitmap Index Scan on ix_pages_lower_live<br>-- condition missing<br>WHERE lower(title) LIKE &#39;annual%&#39;<br>  -&gt;  Seq Scan on pages<br>-- different expression<br>WHERE upper(title) LIKE &#39;ANNUAL%&#39; AND deleted_at IS NULL<br>  -&gt;  Seq Scan on pages</pre><p>Without deleted_at IS NULL, the index would give an incomplete answer, since trashed pages are not in it, so Postgres refuses to use it. With upper() instead of lower(), the stored values simply are not the ones being searched. The practical rule: write the query in one shared function or repository method, so the expression and condition never drift away from the index definition.</p><h3>6. GIN with pg_trgm: finding a word in the middle</h3><p>WHERE lower(title) LIKE &#39;%report%&#39; defeats every B-tree, because matches can begin anywhere. The pg_trgm extension takes a different approach: it splits text into <strong>trigrams</strong>, overlapping three-character pieces. Here is what Postgres actually produces:</p><pre>SELECT show_trgm(&#39;annual report&#39;);<br>-- {&quot;  a&quot;,&quot;  r&quot;,&quot; an&quot;,&quot; re&quot;,&quot;al &quot;,ann,epo,nnu,nua,ort,por,rep,&quot;rt &quot;,ual}</pre><p>Each word is padded with two spaces in front and one at the end, so word boundaries become trigrams too.</p><p>A <strong>GIN</strong> (Generalized Inverted Index) index then stores an inverted list: for each trigram, the rows that contain it.</p><pre>&quot;rep&quot; -&gt; [12, 40, 77, 915, ...]     -- 915: &quot;Repo access&quot;<br>&quot;epo&quot; -&gt; [12, 40, 77, 915, ...]<br>&quot;por&quot; -&gt; [12, 40, 77, 501, ...]     -- 501: &quot;Portal setup&quot;<br>&quot;ort&quot; -&gt; [12, 40, 77, 501, ...]<br>intersection -&gt; [12, 40, 77]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iV-9qvGw-Nq-i6JDCgFRWg.png" /></figure><p><em>Figure 2. A search for “report” intersects the lists for its trigrams and only reads the rows that appear in all of them.</em></p><p>To search for report, Postgres splits the pattern into trigrams (rep, epo, por, ort; the % wildcards mean no word-boundary padding), intersects their lists, and reads only the candidate rows. Because trigrams can match without the whole word matching, every candidate is <strong>rechecked</strong> against the real LIKE, which is the Recheck Cond line in the plan.</p><pre>CREATE EXTENSION IF NOT EXISTS pg_trgm;<br>CREATE INDEX ix_pages_title_trgm<br>    ON pages USING gin (lower(title) gin_trgm_ops)<br>    WHERE deleted_at IS NULL;</pre><pre>-- before<br>Seq Scan on pages (actual rows=3 loops=1)<br>  Rows Removed by Filter: 9997<br>  Buffers: shared hit=70<br>Execution Time: 2.538 ms<br>-- after<br>Bitmap Heap Scan on pages (actual rows=3 loops=1)<br>  Recheck Cond: ((lower(title) ~~ &#39;%report%&#39;::text) AND (deleted_at IS NULL))<br>  Heap Blocks: exact=2<br>  -&gt;  Bitmap Index Scan on ix_pages_title_trgm<br>        Index Cond: (lower(title) ~~ &#39;%report%&#39;::text)<br>Execution Time: 0.056 ms</pre><p>Ten thousand rows scanned before; three matching rows read after, from two table pages.</p><p><strong>Limits and trade-offs:</strong></p><ul><li><strong>Patterns shorter than three characters</strong> produce no useful trigrams. LIKE &#39;%re%&#39; went back to a sequential scan.</li><li><strong>Case-insensitive search does not need </strong><strong>lower().</strong> A trigram index on the raw column also supports ILIKE: WHERE title ILIKE &#39;%REPORT%&#39; used a gin (title gin_trgm_ops) index directly.</li><li><strong>Size and write cost:</strong> every value turns into many index entries, so GIN indexes are larger and slower to update than B-trees (344 kB here versus 288 kB for the B-tree on the same rows). That trade pays off for titles, which are read far more often than written.</li><li><strong>JSONB uses GIN too:</strong> WHERE settings @&gt; &#39;{&quot;beta&quot;: true}&#39; can use a GIN index on a JSONB column, which indexes each key and value.</li></ul><h3>7. GiST: ranges and “these must not overlap”</h3><p>An employee asks for leave from 10 to 15 March. Does it overlap an existing request? Ranges have no single sort order, so a B-tree cannot answer “does any stored range intersect this one?”. A <strong>GiST</strong> index can, because it organizes values as nested bounding regions and quickly discards regions that cannot overlap.</p><p>The strongest use is not a faster query but a rule the database enforces, an <strong>exclusion constraint</strong>:</p><pre>CREATE EXTENSION IF NOT EXISTS btree_gist;<br>ALTER TABLE leave_requests ADD CONSTRAINT no_overlapping_leave<br>    EXCLUDE USING gist (<br>        employee_id WITH =,<br>        daterange(start_date, end_date, &#39;[]&#39;) WITH &amp;&amp;<br>    )<br>    WHERE (status &lt;&gt; &#39;rejected&#39;);</pre><p>Read it as: “no two non-rejected rows may have an equal employee_id and overlapping date ranges.&quot; I inserted 10 to 15 March, then tried 15 to 20 March for the same employee:</p><pre>ERROR:  conflicting key value violates exclusion constraint &quot;no_overlapping_leave&quot;<br>DETAIL:  Key (employee_id, daterange(...))=(57, [2026-03-15,2026-03-21))<br>         conflicts with existing key (employee_id, daterange(...))=(57, [2026-03-10,2026-03-16)).</pre><p>(Postgres stores discrete date ranges in canonical half-open form, which is why the inclusive [15, 20] is printed as [15, 21).)</p><p>16 to 20 March for the same employee, and 10 to 15 March for a different employee, were both accepted. Like a unique index, this closes the race that an application-level overlap check leaves open.</p><p>Three details make or break this constraint:</p><ol><li><strong>btree_gist is required.</strong> Without it, Postgres rejects employee_id WITH = with data type integer has no default operator class for access method &quot;gist&quot;.</li><li><strong>Range bounds.</strong> daterange(a, b) is half-open by default, [a, b), so a request ending on the 15th and one starting on the 15th do <strong>not</strong> overlap. If your end date is inclusive, which it usually is for leave, use &#39;[]&#39;. I checked both: [10,15) &amp;&amp; [15,20) is false, [10,15] &amp;&amp; [15,20] is true.</li><li><strong>The </strong><strong>WHERE clause</strong> keeps rejected requests from blocking new ones.</li></ol><h3>8. Hash indexes</h3><p>Hash indexes support only equality and keep no order. A B-tree handles equality just as well and supports everything else, so in practice you will rarely need one.</p><h3>9. Building indexes in production</h3><p>Everything above is about reading. Creating an index on a live table is an operational event.</p><h4>A plain CREATE INDEX blocks writes</h4><p>A normal CREATE INDEX takes a SHARE lock on the table until it finishes. I started one inside a transaction and, from another session, tried to read and write:</p><pre>-- read during the build<br>SELECT count(*) FROM leave_requests WHERE employee_id = 57;   -&gt; 17<br>-- write during the build (lock_timeout = 1s)<br>INSERT INTO leave_requests ...<br>ERROR:  canceling statement due to lock timeout<br>-- the lock held by the build<br>ShareLock</pre><p>Reads continue; every insert, update and delete waits. On a large table that can mean minutes of failed or hanging writes.</p><h4>CREATE INDEX CONCURRENTLY</h4><pre>CREATE INDEX CONCURRENTLY ix_leave_status ON leave_requests (status);</pre><p>CONCURRENTLY builds the index without blocking writes. It scans the table twice and waits for transactions that might touch it to finish, so it takes longer and does more total work, but users do not notice.</p><p>It has one hard constraint:</p><pre>BEGIN;<br>CREATE INDEX CONCURRENTLY ix_x ON leave_requests (status);<br>ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block</pre><p>Most migration tools wrap each migration in a transaction, so they need an explicit escape hatch for this statement. In Alembic, for example, that is with op.get_context().autocommit_block():.</p><h4>INVALID indexes: worse than none</h4><p>If a concurrent build fails halfway (a timeout, a restart, or a duplicate for a unique index), Postgres leaves the index behind marked <strong>invalid</strong>:</p><pre>CREATE UNIQUE INDEX CONCURRENTLY ux_emp ON leave_requests (employee_id);<br>ERROR:  could not create unique index &quot;ux_emp&quot;<br>DETAIL:  Key (employee_id)=(4864) is duplicated.<br>SELECT indexrelid::regclass, indisvalid FROM pg_index WHERE indexrelid = &#39;ux_emp&#39;::regclass;<br>ux_emp | f</pre><p>An invalid index is never used for queries, but it is still kept up to date on every write. All cost, no benefit. It is also easy to miss, because a rerun with IF NOT EXISTS sees the name and skips:</p><pre>CREATE INDEX IF NOT EXISTS ux_emp ON leave_requests (employee_id);<br>NOTICE:  relation &quot;ux_emp&quot; already exists, skipping</pre><p>A robust migration checks pg_index.indisvalid first and, if the index is invalid, drops it (DROP INDEX CONCURRENTLY) and builds it again, or uses REINDEX INDEX CONCURRENTLY.</p><h4>lock_timeout: fail fast instead of freezing the site</h4><p>Schema changes such as ALTER TABLE need a brief exclusive lock. If a long-running query is holding the table, the migration waits, and here is the dangerous part: <strong>every new query on that table queues behind the waiting migration</strong>. I reproduced it with a long-running transaction holding the table, an ALTER TABLE waiting for it, and a simple lookup arriving afterwards:</p><pre>lock_timeout = 0 (wait forever)  -&gt; the simple SELECT waited 5.1 s, behind the ALTER<br>lock_timeout = 2s                -&gt; the ALTER gave up; the SELECT waited 1.6 s, then ran</pre><p>With a timeout, the migration fails and can be retried later, while the application keeps serving traffic. Without one, a one-millisecond schema change can take the site down for as long as the slowest running query.</p><p><strong>SET versus </strong><strong>SET LOCAL:</strong></p><pre>BEGIN; SET LOCAL lock_timeout = &#39;5s&#39;; COMMIT;<br>SHOW lock_timeout;   -&gt; 0      (reset at the end of the transaction)<br>BEGIN; SET lock_timeout = &#39;5s&#39;; COMMIT;<br>SHOW lock_timeout;   -&gt; 5s     (still active on this connection)</pre><p>SET changes the whole connection. With connection pools or migration runners that reuse one connection, it silently leaks into whatever runs next. Prefer SET LOCAL inside the transaction, or RESET lock_timeout explicitly afterwards.</p><h3>10. Reading EXPLAIN ANALYZE</h3><p>You do not need to read every number. Three signals answer most questions:</p><ul><li><strong>Seq Scan with a large </strong><strong>Rows Removed by Filter</strong> means most of the work was wasted. An index is missing, or the query does not match the one that exists.</li><li><strong>Index Scan, </strong><strong>Index Only Scan or </strong><strong>Bitmap Index Scan</strong> means an index is used. Then check <em>how much</em> of it was read: compare Buffers with the composite example in section 3, where an index was used but read in full.</li><li><strong>Recheck Cond or </strong><strong>Heap Fetches</strong> tells you how much work happened after the index: rechecking lossy matches (GIN, bitmaps) or visiting the table for rows the index could not answer alone.</li></ul><p>Always use EXPLAIN (ANALYZE, BUFFERS) on realistic data. On a tiny development database the planner makes different choices, and a sequential scan there tells you nothing about production.</p><h3>11. When not to add an index</h3><p><strong>Small tables.</strong> With eight rows in public_holidays, Postgres chose a sequential scan even though the unique index existed. Reading one page is faster than walking an index and then the table. The unique index is still worth having there, for the rule, not for speed.</p><p><strong>Low-selectivity filters.</strong> About 90% of leave requests are approved. With an index on status:</p><pre>WHERE status = &#39;approved&#39;  (90%)  -&gt;  Seq Scan<br>WHERE status = &#39;pending&#39;   (5%)   -&gt;  Bitmap Index Scan</pre><p>When a query returns most of the table, reading the table directly is cheaper. If only the rare value matters, a partial index is smaller and sharper: CREATE INDEX ON leave_requests (start_date) WHERE status = &#39;pending&#39; was 80 kB and served &quot;the oldest pending requests&quot; with a plain index scan.</p><p><strong>Write-heavy tables.</strong> Every index is updated on every insert. Inserting 100,000 rows into an audit-style table took 289 ms with only a primary key and 857 ms with four extra indexes, about three times slower. For logs and audit trails that are written constantly and read rarely, index only what you actually query.</p><h3>Summary</h3><ol><li>Design indexes from <strong>queries</strong>, not tables: look at WHERE, JOIN and ORDER BY.</li><li>The query must match the index’s <strong>shape</strong>: the same expression, the same partial condition, the leading columns of a composite index, and the right operator class for LIKE.</li><li>Use the database for rules that must hold under concurrency: <strong>unique</strong> indexes and <strong>exclusion</strong> constraints, not check-then-write code.</li><li>In production, build with <strong>CONCURRENTLY</strong>, set <strong>lock_timeout</strong>, and watch for <strong>invalid</strong> indexes.</li><li>When in doubt, run <strong>EXPLAIN (ANALYZE, BUFFERS)</strong> on realistic data. Do not guess.</li></ol><h3>Exercises</h3><ol><li><strong>Composite order.</strong> For WHERE status = &#39;pending&#39; AND created_at &gt; now() - interval &#39;7 days&#39; ORDER BY created_at, which column order would you choose for a composite index, and why? Verify with EXPLAIN.</li><li><strong>Find the race.</strong> Pick a place in an application you know that does “check, then insert”. Describe the duplicate it could create under concurrency, and the constraint that would prevent it.</li><li><strong>Index audit.</strong> Run this on a real database and explain each result: SELECT indexrelid::regclass, idx_scan FROM pg_stat_user_indexes ORDER BY idx_scan LIMIT 10; (indexes that are never scanned) and SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid; (invalid indexes).</li><li><strong>Inclusive ranges.</strong> Write a test that proves your overlap rule treats a leave ending on the 15th and one starting on the 15th the way your business expects.</li></ol><h3>References</h3><ul><li>PostgreSQL documentation, <a href="https://www.postgresql.org/docs/current/indexes.html">Indexes</a>, especially <a href="https://www.postgresql.org/docs/current/indexes-multicolumn.html">Multicolumn Indexes</a>, <a href="https://www.postgresql.org/docs/current/indexes-partial.html">Partial Indexes</a>, <a href="https://www.postgresql.org/docs/current/indexes-expressional.html">Indexes on Expressions</a> and <a href="https://www.postgresql.org/docs/current/indexes-index-only-scans.html">Index-Only Scans and Covering Indexes</a>.</li><li>PostgreSQL documentation, <a href="https://www.postgresql.org/docs/current/indexes-opclass.html">Operator Classes</a>, on text_pattern_ops and LIKE.</li><li>PostgreSQL documentation, <a href="https://www.postgresql.org/docs/current/pgtrgm.html">pg_trgm</a> and <a href="https://www.postgresql.org/docs/current/btree-gist.html">btree_gist</a>.</li><li>PostgreSQL documentation, <a href="https://www.postgresql.org/docs/current/sql-createindex.html">CREATE INDEX</a>, section “Building Indexes Concurrently”.</li><li>PostgreSQL documentation, <a href="https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-EXCLUSION">Exclusion constraints</a>.</li><li>PostgreSQL 18 <a href="https://www.postgresql.org/docs/release/18/">release notes</a>, B-tree skip scan.</li><li>Markus Winand, <a href="https://use-the-index-luke.com/">Use The Index, Luke!</a>, the best free deep dive on how indexes and query plans interact.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8da3a0f0e13f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Python’s list, dict, set and tuple: How They Are Built and What They Really Cost]]></title>
            <link>https://medium.com/@hajaghahasanli/inside-pythons-list-dict-set-and-tuple-how-they-are-built-and-what-they-really-cost-6f9aec4c61a1?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f9aec4c61a1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-10-23T07:01:03.942Z</atom:updated>
            <content:encoded><![CDATA[<h4>Big-O tables are a summary. This is the machinery behind them, measured on CPython 3.13.</h4><p>A service deduplicates incoming events by checking if event_id in seen_ids before processing each one. With a few hundred events it is instant. A month later the same code takes minutes per batch. Nothing changed except volume, and seen_ids was a list.</p><p>Every Python developer has seen a Big-O table that says list membership is O(n) and set membership is O(1). Fewer can explain <em>why</em>, what “amortized” hides, when a dict lookup degrades to O(n), or why a dict that you emptied still uses five megabytes. Those details decide how code behaves under real load.</p><p>This article opens up the four core containers as CPython implements them: what is in memory, what each operation actually does, and where the textbook complexities stop being true. Every number below was measured, not quoted.</p><h3>What you will be able to do</h3><ol><li>Describe the memory layout of list, dict, set and tuple in CPython.</li><li>Explain amortized O(1) append using the real over-allocation pattern.</li><li>Explain how a hash table finds a key, why load factor matters, and what makes lookups degrade to O(n).</li><li>Predict which operations are cheap and which are linear, and pick the right container for an access pattern.</li><li>Recognize CPython-specific behaviors that matter in production: dicts that never shrink, randomized string hashes and constant-folded tuples.</li></ol><p><strong>Prerequisites:</strong> the previous article in this series on names, references and mutability, and a basic idea of Big-O notation. <strong>Environment for all measurements:</strong> CPython 3.13.16 on Linux x86–64, a 2-vCPU Intel Xeon at 2.8 GHz. Absolute timings will differ on your machine; the ratios are the point.</p><h3>1. One idea underneath all four: containers hold references</h3><p>None of these containers store your objects inline. A list of a million integers is an array of a million <em>pointers</em>, each pointing at an integer object elsewhere in memory. On a 64-bit build each pointer is 8 bytes.</p><p>This explains several things at once. Containers can hold mixed types, because a pointer is a pointer. Copying a list copies pointers, not objects, which is why shallow copies share their contents. And the “cost” of an operation is mostly about how many pointers or hash table slots CPython has to touch.</p><h3>2. list: a dynamic array of pointers</h3><p>In CPython a list is a small header plus a separately allocated, contiguous array of pointers. The header tracks two numbers: how many items the list holds (len) and how many slots are allocated (its <em>capacity</em>).</p><p>Indexing is O(1) because the address of item i is simply start + i * 8. Nothing is searched.</p><h4>Why append is &quot;amortized O(1)&quot;</h4><p>If a list allocated exactly as many slots as it needed, every append would require a new, larger array and a copy of all existing pointers: O(n) per append and O(n²) for a loop of appends. CPython avoids this by <strong>over-allocating</strong>. When the array is full, it grows by roughly an eighth of the new size plus a small constant, rounded to a multiple of 4. The comment in Objects/listobject.c documents the pattern as 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, …</p><p>You can watch it happen:</p><pre>import sys<br>items = []<br>empty = sys.getsizeof(items)<br>last_capacity = 0<br>for i in range(70):<br>    items.append(i)<br>    capacity = (sys.getsizeof(items) - empty) // 8   # 8-byte pointers on 64-bit<br>    if capacity != last_capacity:<br>        print(f&quot;len={len(items):&gt;3}  capacity={capacity}&quot;)<br>        last_capacity = capacity</pre><p>Output:</p><pre>len=  1  capacity=4<br>len=  5  capacity=8<br>len=  9  capacity=16<br>len= 17  capacity=24<br>len= 25  capacity=32<br>len= 33  capacity=40<br>len= 41  capacity=52<br>len= 53  capacity=64<br>len= 65  capacity=76</pre><p>Most appends write into a slot that already exists. Only occasionally does the list reallocate and copy. Spread over many appends, the copying cost per append is a constant, which is what <strong>amortized O(1)</strong> means: not “every append is fast”, but “the average over a long sequence is constant”. A single append that triggers a resize is still O(n). In latency-sensitive code that occasional spike can matter.</p><p>Note that the growth factor is modest (about 1.125× for large lists). CPython trades a little extra copying for less wasted memory, and relies on the system allocator often being able to extend a block in place.</p><h4>The expensive end of a list</h4><p>Appending and popping at the <em>end</em> is cheap. Inserting or removing at the <em>front</em> is not: every following pointer has to shift one slot.</p><pre>from collections import deque<br>from timeit import timeit<br>N = 100_000<br>print(&quot;append      &quot;, round(timeit(&quot;x.append(0)&quot;, &quot;x=[]&quot;, number=N), 4), &quot;s&quot;)<br>print(&quot;insert(0, ) &quot;, round(timeit(&quot;x.insert(0, 0)&quot;, &quot;x=[]&quot;, number=N), 4), &quot;s&quot;)<br>print(&quot;appendleft  &quot;, round(timeit(&quot;x.appendleft(0)&quot;, &quot;from collections import deque; x=deque()&quot;, number=N), 4), &quot;s&quot;)</pre><p>Output:</p><pre>append       0.0049 s<br>insert(0, )  1.1802 s<br>appendleft   0.0036 s</pre><p>One hundred thousand front insertions took about 240 times longer than appends, and the gap grows with size because each insertion is O(n). If you need a queue, use collections.deque, which is implemented as a doubly linked list of fixed-size blocks and supports O(1) operations at both ends. The trade-off: indexing into the middle of a deque is O(n).</p><h4>list cost summary</h4><pre>Operation              Cost<br>x[i], x[i] = v         O(1)<br>append, pop()          O(1) amortized<br>insert(i, v), pop(i)   O(n - i)<br>x in list              O(n)<br>x[a:b]                 O(b - a)<br>sort                   O(n log n)</pre><h3>3. dict: a compact, ordered hash table</h3><p>A dict has to answer “where is this key?” without scanning every key. It does that with <strong>hashing</strong>: hash(key) produces an integer, and that integer, reduced to the table size, selects a slot.</p><h4>The layout since Python 3.6</h4><p>Older dicts were a single sparse array of (hash, key, value) entries, mostly empty. Since CPython 3.6 the dict is <strong>split into two arrays</strong>, as described at the top of Objects/dictobject.c:</p><ul><li><strong>dk_indices</strong>: the actual hash table. A sparse array of small integers. Each slot is either empty, a &quot;dummy&quot; marker left by a deletion, or an index into the entries array.</li><li><strong>dk_entries</strong>: a dense array of (hash, key, value) records, appended in insertion order.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzL9DGQJo07AK8a5qYg1vA.png" /></figure><p><em>Figure 1. A lookup hashes the key, probes </em><em>dk_indices, follows the stored index into </em><em>dk_entries, and compares the key. Because entries are appended, iterating </em><em>dk_entries yields insertion order.</em></p><p>This design does two useful things. Memory drops, because the sparse part now holds 1-, 2-, 4- or 8-byte indices instead of 24-byte entries. And iteration order becomes insertion order for free, since the entries array is mostly append-only. Insertion order was an implementation detail in 3.6 and became a <strong>language guarantee in Python 3.7</strong>.</p><h4>How a lookup works</h4><ol><li>Compute hash(key).</li><li>Take the low bits of the hash as the first slot in dk_indices.</li><li>If the slot is empty, the key is absent. If it holds an index, go to that entry and compare: first identity (is), then the stored hash, and only if the hashes match, ==.</li><li>If the slot belongs to a different key (a <strong>collision</strong>), compute the next slot from a recurrence that mixes in progressively higher bits of the hash (perturb) and try again.</li></ol><p>This is <strong>open addressing</strong>: collisions are resolved by probing other slots in the same table, not by chaining lists off each slot.</p><h4>Load factor and resizing</h4><p>Probing stays short only while the table has plenty of empty slots. CPython resizes the table when it becomes <strong>two-thirds full</strong> (the USABLE_FRACTION). Resizing allocates a bigger table and reinserts every entry, which is O(n). As with list.append, it happens rarely enough that insertion is amortized O(1).</p><h4>When O(1) becomes O(n): collisions</h4><p>The average-case O(1) assumes that hashes spread keys evenly. If many keys share a hash, every lookup has to probe past all of them. Here is a deliberately terrible hash function:</p><pre>from timeit import timeit<br>class BadKey:<br>    __slots__ = (&quot;value&quot;,)<br>    def __init__(self, value):<br>        self.value = value<br>    def __hash__(self):<br>        return 42                      # every key lands in the same place<br>    def __eq__(self, other):<br>        return self.value == other.value<br>class GoodKey(BadKey):<br>    __slots__ = ()<br>    def __hash__(self):<br>        return hash(self.value)<br>for cls in (GoodKey, BadKey):<br>    for n in (1_000, 2_000, 4_000):<br>        keys = [cls(i) for i in range(n)]<br>        t = timeit(lambda: {k: None for k in keys}, number=1)<br>        print(f&quot;{cls.__name__:&lt;8} n={n:&lt;5} {t * 1000:8.2f} ms&quot;)</pre><p>Output:</p><pre>GoodKey  n=1000      0.13 ms<br>GoodKey  n=2000      0.26 ms<br>GoodKey  n=4000      0.51 ms<br>BadKey   n=1000     26.74 ms<br>BadKey   n=2000    106.97 ms<br>BadKey   n=4000    452.43 ms</pre><p>With a good hash, doubling the number of keys doubles the time: linear for n insertions, O(1) each. With a constant hash, doubling the keys roughly <strong>quadruples</strong> the time: each insertion is O(n), so building the dict is O(n²). At 4,000 keys it is almost 900 times slower.</p><p>This is not only a contrived problem. If attackers can choose keys whose hashes collide, they can turn a web server’s request parsing into quadratic work, a well-known denial-of-service technique. That is why CPython <strong>randomizes the hashes of </strong><strong>str and </strong><strong>bytes</strong> per process:</p><pre>import subprocess, sys<br>cmd = [sys.executable, &quot;-c&quot;, &quot;print(hash(&#39;birmenzil&#39;), hash(42))&quot;]<br>for _ in range(2):<br>    print(subprocess.run(cmd, capture_output=True, text=True).stdout.strip())</pre><p>Output:</p><pre>-1592336260020378173 42<br>1803995404419505282 42</pre><p>The string’s hash changes between runs; the integer’s doesn’t. Two practical consequences: never persist hash() values of strings (use hashlib for stable hashes), and never rely on set iteration order for strings, because it can change from one run to the next.</p><h4>Rules for a good key</h4><p>A dict key must be hashable, and the hash must agree with equality: if a == b, then hash(a) == hash(b). It must also never change while the object is in a dict. This is why mutable built-ins are unhashable, and why a class that defines __eq__ without __hash__ becomes unhashable. Python refuses to guess a hash that might break the rule.</p><h4>A dict never shrinks on its own</h4><pre>import sys<br>d = {i: i for i in range(100_000)}<br>print(&quot;full:        &quot;, sys.getsizeof(d))<br>for i in range(100_000):<br>    del d[i]<br>print(&quot;after delete:&quot;, sys.getsizeof(d), &quot;len =&quot;, len(d))<br>d = dict(d)                          # rebuild to release the memory<br>print(&quot;rebuilt:     &quot;, sys.getsizeof(d))</pre><p>Output:</p><pre>full:         5242960<br>after delete: 5242960 len = 0<br>rebuilt:      64</pre><p>Deleting marks slots as dummies; it does not resize the table. An empty dict that once held 100,000 items still occupies about 5 MB, and iterating it still walks the old entries array. This is why the Big-O table on the Python wiki notes that, for dict iteration, n is the <strong>maximum size the dict ever reached</strong>. For long-lived caches with heavy churn, rebuild the dict periodically or use a structure designed for eviction.</p><h4>Iteration and mutation</h4><pre>d = {}<br>d[&quot;b&quot;] = 1<br>d[&quot;a&quot;] = 2<br>d[&quot;c&quot;] = 3<br>print(list(d))                      # insertion order, guaranteed since 3.7<br>s = {&quot;b&quot;, &quot;a&quot;, &quot;c&quot;}<br>print(s == {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;})         # sets compare by content; their order is not guaranteed<br>try:<br>    for key in d:<br>        d[key + key] = 0<br>except RuntimeError as e:<br>    print(&quot;RuntimeError:&quot;, e)</pre><p>Output:</p><pre>[&#39;b&#39;, &#39;a&#39;, &#39;c&#39;]<br>True<br>RuntimeError: dictionary changed size during iteration</pre><p>Adding keys during iteration could trigger a resize that rebuilds the arrays being iterated, so CPython detects size changes and raises. Iterate over list(d) if you need to modify the dict in the loop.</p><h4>dict cost summary</h4><pre>Operation          Average   Worst case<br>d[k], d[k] = v     O(1)      O(n)  (collisions)<br>del d[k]           O(1)      O(n)<br>k in d             O(1)      O(n)<br>iteration          O(n)      n = peak size<br>copy               O(n)      n = peak size</pre><h3>4. set: a hash table without values</h3><p>A set is a hash table of keys only. The rules for members are the same as for dict keys, and membership is average O(1):</p><pre>from timeit import timeit<br>setup = &quot;data_list = list(range(1_000_000)); data_set = set(data_list); target = 999_999&quot;<br>print(&quot;list:&quot;, round(timeit(&quot;target in data_list&quot;, setup, number=100) / 100 * 1e6, 1), &quot;µs per lookup&quot;)<br>print(&quot;set: &quot;, round(timeit(&quot;target in data_set&quot;, setup, number=100) / 100 * 1e6, 3), &quot;µs per lookup&quot;)</pre><p>Output:</p><pre>list: 8376.4 µs per lookup<br>set:  0.079 µs per lookup</pre><p>For a million items, the list scans every element (about 8 ms); the set computes a hash and probes a slot (about 80 ns). That is a factor of roughly 100,000, which is the opening bug in one number.</p><p>The set implementation is not just a dict without values. Objects/setobject.c describes a <strong>hybrid of linear probing and randomized probing</strong>: each probe first checks a few neighboring slots, which are likely to be in the same CPU cache line, before jumping elsewhere. Unlike dicts, sets do <strong>not</strong> keep an ordered entries array, so set iteration order is arbitrary and, for strings, varies between runs.</p><p>Set algebra has its own costs. Union is O(len(s) + len(t)). Intersection iterates over the smaller set and checks the larger, so it is O(min(len(s), len(t))) on average. Difference s - t is O(len(s)).</p><p>Building a set is O(n), so converting a list to a set only pays off if you will do more than a handful of lookups. For one membership check, scanning the list is cheaper than hashing every element.</p><h3>5. tuple: a fixed-size array, and why that matters</h3><p>A tuple is an immutable, fixed-length array of pointers stored inline with its header. Because it never grows, it needs no separate buffer and no spare capacity.</p><pre>import dis, sys<br>from timeit import timeit<br>print(sys.getsizeof([1, 2, 3]), sys.getsizeof((1, 2, 3)))<br>print(timeit(&quot;[1, 2, 3]&quot;, number=5_000_000) &gt; timeit(&quot;(1, 2, 3)&quot;, number=5_000_000))<br>dis.dis(compile(&quot;x = (1, 2, 3)&quot;, &quot;&lt;demo&gt;&quot;, &quot;exec&quot;))<br>dis.dis(compile(&quot;x = [1, 2, 3]&quot;, &quot;&lt;demo&gt;&quot;, &quot;exec&quot;))</pre><p>Output (bytecode trimmed to the relevant lines):</p><pre>88 64<br>True<br>LOAD_CONST               0 ((1, 2, 3))<br>STORE_NAME               0 (x)<br>BUILD_LIST               0<br>LOAD_CONST               0 ((1, 2, 3))<br>LIST_EXTEND              1<br>STORE_NAME               0 (x)</pre><p>Three things stand out:</p><ul><li>The tuple is smaller: 64 bytes versus 88 for the same three items.</li><li>A tuple literal made of constants is <strong>built once at compile time</strong> and stored in the code object. Executing x = (1, 2, 3) is a single LOAD_CONST. The list literal must create a new list every time, because each execution must produce a fresh mutable object.</li><li>Immutability makes tuples hashable when their contents are, so they can be dict keys and set members. Composite keys like (user_id, date) are a classic use.</li></ul><p>Choose a tuple when the number of fields is fixed and meaningful (a record, a coordinate, a key). Choose a list when the collection grows or changes.</p><h3>6. New in Python 3.15: frozendict</h3><p>Python 3.15, released on October 9, 2026, adds a built-in frozendict (PEP 814). It is not a dict subclass. It has no mutating methods, it preserves insertion order, and it is hashable when all of its keys and values are hashable. It fills the gap that used to be covered by types.MappingProxyType (a read-only <em>view</em> of a dict that can still change underneath) or by tuples of pairs: immutable configuration, cache keys built from mappings, and defaults that must not be modified.</p><h3>7. Choosing a container</h3><pre>Need                                     Use<br>Ordered, growing sequence; index access  list<br>Queue / work list (add and remove ends)  collections.deque<br>Fast membership / dedup                  set (frozenset if it must be hashable)<br>Key -&gt; value lookup                      dict (frozendict in 3.15+ if immutable)<br>Fixed record; hashable composite key     tuple (or a named tuple / dataclass)<br>Counting                                 collections.Counter (a dict subclass)</pre><p>A senior-level habit: look at the <strong>operation inside the loop</strong>, not at the container. x in list once is fine. x in list inside a loop over another list is O(n·m), and that pattern is behind a large share of &quot;it was fast in testing&quot; incidents.</p><h3>Exercises</h3><p><strong>Level 1 — Understanding.</strong> Using sys.getsizeof, find out whether list(range(10)) and a list built with ten append calls have the same capacity. Explain the difference.</p><p><strong>Level 2 — Implementation.</strong> Write a function that returns the items two lists have in common, preserving the order of the first list. <em>Acceptance:</em> O(n + m) average time, correct handling of duplicates (decide and document the behavior), and a test with 100,000 items that finishes in well under a second.</p><p><strong>Level 3 — Engineering judgment.</strong> A long-running worker keeps a dict of in-flight job IDs. Jobs are added and removed thousands of times per second, but rarely more than 1,000 are in flight at once. Memory grows over days. Explain the likely cause using what you learned about deletions and peak size, and propose two fixes with their trade-offs.</p><p><strong>Level 4 — Challenge.</strong> Implement a minimal open-addressing hash map in pure Python (a fixed-size slots array, linear probing, resize at two-thirds load, tombstones for deletion). Write tests for collisions, deletion followed by lookup of a colliding key, and resizing. Compare its insert time against dict for 100,000 keys.</p><h3>Knowledge check</h3><ol><li>What does “amortized O(1)” mean for list.append, and when is a single append not O(1)?</li><li>Why is x.insert(0, v) slow for a large list, and what would you use instead?</li><li>In the compact dict layout, what is stored in dk_indices and what is stored in dk_entries? Why does this layout give insertion order?</li><li>Give two situations in which dict lookups degrade toward O(n).</li><li>Why does hash(&quot;text&quot;) change between Python processes while hash(42) doesn&#39;t?</li><li>A dict had a million entries and you deleted them all. What happens to memory and iteration time, and how do you fix it?</li><li>Interview question: “Why is checking membership in a set faster than in a list? Is it always?”</li></ol><h4>Answers</h4><ol><li>Over a long sequence of appends the total copying work is proportional to the number of appends, so the average cost per append is constant. An append that hits capacity triggers a reallocation and copy of all pointers, which is O(n) for that one call.</li><li>Every existing pointer shifts one slot to the right, so the cost is O(n). Use collections.deque.appendleft, which is O(1).</li><li>dk_indices is the sparse hash table holding small integers that index into dk_entries. dk_entries holds (hash, key, value) records in the order they were added. Iterating the dense entries array therefore yields insertion order.</li><li>When many keys share hash values (a poor __hash__ or an adversarial input), and, for iteration and copying, when the dict once grew much larger than its current size.</li><li>str and bytes hashes are randomized per process to protect against collision-based denial-of-service attacks. Integers hash to their own value (for all but very large values), so their hashes are stable.</li><li>The table keeps its peak size; memory is not released, and iteration still walks the old entries. Rebuild it with d = dict(d) (or create a new dict) to release the memory.</li><li>A set computes the hash and probes a few slots, which is O(1) on average; a list compares items one by one, O(n). Not always: with heavy hash collisions a set degrades toward O(n), and for a single lookup, building the set first (O(n)) costs more than scanning the list once.</li></ol><h3>Summary and mastery criteria</h3><ul><li>Containers store pointers, not objects.</li><li>list is a dynamic array: O(1) at the end, O(n) at the front. Over-allocation makes append amortized O(1).</li><li>dict is a compact hash table: a sparse index array plus a dense, insertion-ordered entries array. Average O(1), worst O(n), resized at two-thirds full, never shrunk by deletions.</li><li>set is a key-only hash table with cache-friendly probing and no guaranteed order.</li><li>tuple is a fixed array: smaller, constant-folded when built from literals, and hashable when its contents are.</li></ul><p>You have this topic when you can draw the compact dict layout from memory, explain the BadKey timings, choose the right container for a described access pattern, and complete the Level 2 exercise with a measured runtime.</p><h3>References</h3><ul><li>CPython source, <a href="https://github.com/python/cpython/blob/3.13/Objects/listobject.c">Objects/listobject.c</a> — list_resize and the over-allocation growth pattern.</li><li>CPython source, <a href="https://github.com/python/cpython/blob/3.13/Objects/dictobject.c">Objects/dictobject.c</a> — the comments at the top describe the compact layout, USABLE_FRACTION and the probing recurrence.</li><li>CPython source, <a href="https://github.com/python/cpython/blob/3.13/Objects/setobject.c">Objects/setobject.c</a> — the hybrid linear and randomized probing scheme.</li><li>Python Wiki, <a href="https://wiki.python.org/moin/TimeComplexity">TimeComplexity</a> — average and amortized worst-case costs, including the note on peak size.</li><li>Python Library Reference, <a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict">Mapping types — dict</a> — insertion order guaranteed since 3.7.</li><li>Python Language Reference, <a href="https://docs.python.org/3/reference/datamodel.html#object.__hash__">object.__hash__</a> — hash/equality rules and hash randomization.</li><li><a href="https://peps.python.org/pep-0814/">PEP 814 — frozendict</a>, part of Python 3.15.</li><li>Luciano Ramalho, <em>Fluent Python</em>, 2nd Edition, Chapters 2 and 3 — sequences, dicts and sets, with more on the practical consequences of hash tables.</li></ul><p><em>Next in this series: comprehensions, unpacking and slicing, and what the syntax actually compiles to.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f9aec4c61a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Names Are Not Boxes: Identity, Mutability and Copies]]></title>
            <link>https://medium.com/@hajaghahasanli/python-names-are-not-boxes-identity-mutability-and-copies-dd6711c12b05?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd6711c12b05</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 10:22:44 GMT</pubDate>
            <atom:updated>2026-10-21T10:22:44.046Z</atom:updated>
            <content:encoded><![CDATA[<h4>A working mental model of Python’s object model, with every example executed and tested</h4><p>Here is a bug that is easy to ship. A function builds per-user settings from a shared DEFAULTS dict, applies a few overrides and returns the result. In tests everything passes. In production, one user enables a beta feature and suddenly every user has it.</p><p>Nothing about the code looks wrong at first glance. The problem is a mental model: the author thought dict(DEFAULTS) produced an independent copy. It produces a new outer dict whose values are the <em>same</em> inner objects. Changing the inner dict for one user changed it for everyone.</p><p>This article builds the mental model that makes this bug obvious: what a Python variable actually is, what “mutable” really means, why is and == are different questions, how function arguments are passed, and what a copy does and does not copy.</p><h3>What you will be able to do</h3><p>After working through this article you should be able to:</p><ol><li>Explain the difference between a name and an object, and predict when two names share one object.</li><li>Distinguish identity (is) from equality (==) and know when each is the right check.</li><li>Classify every built-in type as mutable or immutable, hashable or unhashable, and explain why.</li><li>Tell mutation apart from rebinding, including the in-place behavior of +=.</li><li>Predict what a function can and cannot change in the caller’s data.</li><li>Recognize and fix the mutable default argument bug.</li><li>Choose between sharing, a shallow copy, a deep copy and an immutable structure, and test that the choice holds.</li></ol><p><strong>Prerequisites:</strong> you can read basic Python syntax. If you know JavaScript, you already know half of this model: JS objects and arrays behave the same way when assigned or passed to functions. The difference is that in Python <em>everything</em> is an object, including integers, strings, functions and classes.</p><h3>1. Every value is an object with three properties</h3><p>The Python language reference defines objects this way: every object has an <strong>identity</strong>, a <strong>type</strong> and a <strong>value</strong>.</p><ul><li><strong>Identity</strong> never changes once the object is created. You can think of it as the object’s address in memory. id(x) returns it as an integer, and the is operator compares identities.</li><li><strong>Type</strong> determines what operations the object supports and what values it can hold. type(x) returns it. Like identity, it does not change.</li><li><strong>Value</strong> may or may not be changeable. Objects whose value can change are <strong>mutable</strong>; objects whose value cannot change are <strong>immutable</strong>. Mutability is a property of the type: lists and dicts are mutable, while numbers, strings and tuples are immutable.</li></ul><p>That is the whole foundation. Everything else in this article follows from it.</p><h3>2. Names are labels, not boxes</h3><p>A common mental model from other languages is that a variable is a box that contains a value. In Python, a variable is a <strong>name bound to an object</strong>. Assignment never copies data. It makes a name refer to an object.</p><pre>cart = [&quot;apple&quot;, &quot;bread&quot;]<br>order = cart              # no copy: a second name for the same list<br>order.append(&quot;milk&quot;)<br>print(cart)               # the change is visible through both names<br>print(order is cart)      # same object?<br>print(id(order) == id(cart))</pre><p>Output:</p><pre>[&#39;apple&#39;, &#39;bread&#39;, &#39;milk&#39;]<br>True<br>True</pre><p>order = cart creates a second label for the same list. This is called <strong>aliasing</strong>. The official Python FAQ describes it directly: y = x doesn&#39;t create a copy of the list, it creates a new variable that refers to the same object.</p><p>A useful way to read assignment is right to left: first the right-hand side produces an object (or finds an existing one), then the name on the left is bound to it.</p><h3>3. Identity versus equality</h3><p>== asks: <em>do these two objects have the same value?</em> It calls the type&#39;s __eq__ method. is asks: <em>are these the same object?</em> It compares identities and cannot be overridden.</p><pre>a = [1, 2, 3]<br>b = [1, 2, 3]<br>print(a == b)     # equal values<br>print(a is b)     # different objects<br>print(type(a), type(a) is list)<br>result = None<br>print(result is None)  # the idiomatic check for the None singleton</pre><p>Output:</p><pre>True<br>False<br>&lt;class &#39;list&#39;&gt; True<br>True</pre><p>Use is for singletons such as None (and sentinel objects you create yourself). Use == for values.</p><h4>Why you must not use is to compare values</h4><p>For immutable types, Python is allowed to reuse existing objects. The language reference says that after a = 1; b = 1, a and b may or may not refer to the same object, depending on the implementation. CPython does reuse some objects as an optimization:</p><pre>import sys<br>def make(s):<br>    return int(s)                    # build ints at runtime, not as literals<br>print(make(&quot;256&quot;) is make(&quot;256&quot;))    # CPython small-int cache<br>print(make(&quot;257&quot;) is make(&quot;257&quot;))<br>a = &quot;&quot;.join([&quot;hello&quot;, &quot;-&quot;, &quot;world&quot;])<br>b = &quot;&quot;.join([&quot;hello&quot;, &quot;-&quot;, &quot;world&quot;])<br>print(a == b, a is b)<br>print(sys.intern(a) is sys.intern(b))<br>print(sys.version.split()[0])</pre><p>Output:</p><pre>True<br>False<br>True False<br>True<br>3.13.16</pre><p>CPython 3.13 keeps a cache of small integer objects from −5 to 256, so 256 is 256 happens to be True while 257 is 257 (built at runtime) is False. This is documented as an <strong>implementation detail</strong>: the documentation for newer CPython versions already describes a larger range. Strings may or may not be shared, and sys.intern() lets you request sharing explicitly.</p><p>Code that uses is to compare numbers or strings can pass every test today and break on another Python version or implementation. == for values, is for identity.</p><h3>4. The built-in types at a glance</h3><p>Here is the map you need for the rest of the article. <strong>Hashable</strong> means the object has a hash value that never changes during its lifetime, which is what dict keys and set members require.</p><pre>Type       Mutable?  Hashable?                           Notes<br>int        No        Yes                                 Arbitrary precision; no overflow<br>float      No        Yes                                 IEEE 754 double precision<br>bool       No        Yes                                 A subclass of int<br>complex    No        Yes<br>str        No        Yes                                 A sequence of Unicode code points<br>bytes      No        Yes                                 A sequence of raw bytes (0–255)<br>bytearray  Yes       No                                  Mutable counterpart of bytes<br>tuple      No        Only if all its items are hashable<br>list       Yes       No<br>dict       Yes       No                                  Keys must be hashable<br>set        Yes       No                                  Members must be hashable<br>frozenset  No        Yes                                 Immutable counterpart of set<br>NoneType   No        Yes                                 A single object: None</pre><p>A few properties in this table regularly surprise engineers coming from JavaScript or TypeScript:</p><pre>print(2 ** 100)                     # ints have arbitrary precision<br>print(0.1 + 0.2 == 0.3, 0.1 + 0.2)  # floats are IEEE 754 binary doubles<br>from decimal import Decimal<br>print(Decimal(&quot;0.1&quot;) + Decimal(&quot;0.2&quot;) == Decimal(&quot;0.3&quot;))<br>print(isinstance(True, int), True + True)   # bool is a subclass of int<br>print({1: &quot;one&quot;, True: &quot;true&quot;})             # 1 == True and hash(1) == hash(True)<br>text = &quot;Bakı&quot;<br>data = text.encode(&quot;utf-8&quot;)<br>print(len(text), len(data), data)           # str = code points, bytes = raw bytes</pre><p>Output:</p><pre>1267650600228229401496703205376<br>False 0.30000000000000004<br>True<br>True 2<br>{1: &#39;true&#39;}<br>4 5 b&#39;Bak\xc4\xb1&#39;</pre><ul><li>Python integers grow as needed. There is no Number.MAX_SAFE_INTEGER equivalent and no BigInt split.</li><li>Floats have the same binary rounding behavior as JavaScript numbers. Use decimal.Decimal for money.</li><li>Because True == 1 and they hash identically, they collide as dict keys. The dict keeps the first key object and the last value.</li><li>len() of a str counts code points, not bytes. The Azerbaijani &quot;ı&quot; takes two bytes in UTF-8.</li></ul><h3>5. Mutation versus rebinding</h3><p>This distinction explains most “why did that change?” moments.</p><ul><li><strong>Mutation</strong> changes the value of an existing object. Every name bound to that object sees the change.</li><li><strong>Rebinding</strong> points a name at a different object. Other names are unaffected.</li></ul><p>The augmented assignment operators make this subtle. The language reference says x += y is performed <strong>in place when possible</strong>: if the type implements __iadd__, the object is mutated; otherwise Python computes x + y and rebinds x to the new object.</p><pre>nums = [1, 2]<br>before = id(nums)<br>nums += [3]                  # list.__iadd__: mutates in place<br>print(nums, id(nums) == before)<br>nums = nums + [4]            # list.__add__: builds a NEW list, then rebinds the name<br>print(nums, id(nums) == before)<br>word = &quot;py&quot;<br>before = id(word)<br>word += &quot;thon&quot;               # str has no __iadd__: a new string is created<br>print(word, id(word) == before)<br>point = (1, 2)<br>before = id(point)<br>point += (3,)                # same for tuples<br>print(point, id(point) == before)</pre><p>Output:</p><pre>[1, 2, 3] True<br>[1, 2, 3, 4] False<br>python False<br>(1, 2, 3) False</pre><p>So += on a list mutates it, which every alias will see, while += on a string or tuple creates a new object and rebinds only that one name. Same operator, different semantics, decided by the type.</p><h3>6. How function arguments are passed</h3><p>Python passes arguments <strong>by assignment</strong>: the parameter name inside the function is bound to the same object the caller passed. This is sometimes called <em>call by sharing</em>. It is neither “pass by value” (no copy is made) nor “pass by reference” (the function cannot rebind the caller’s variable).</p><pre>def add_tag(tags):<br>    tags.append(&quot;python&quot;)     # mutates the caller&#39;s object<br>def replace_tags(tags):<br>    tags = [&quot;rust&quot;]           # rebinds the LOCAL name only<br>    return tags<br>my_tags = [&quot;react&quot;]<br>add_tag(my_tags)<br>print(my_tags)<br>result = replace_tags(my_tags)<br>print(my_tags, result)</pre><p>Output:</p><pre>[&#39;react&#39;, &#39;python&#39;]<br>[&#39;react&#39;, &#39;python&#39;] [&#39;rust&#39;]</pre><p>Two rules fall out of this:</p><ol><li>A function <strong>can</strong> change a mutable argument’s value, and the caller will see it.</li><li>A function <strong>cannot</strong> make the caller’s name point somewhere else. To give the caller a new object, return it.</li></ol><p>This is exactly how JavaScript treats objects and arrays. The practical consequence for API design is the same too: a function that mutates its input should say so in its name or docstring, and most functions should not do it at all.</p><h3>7. The mutable default argument</h3><p>The language reference is explicit: <strong>default parameter values are evaluated once, when the function definition is executed</strong>, and the same object is used for every call.</p><pre>def add_item_buggy(item, bucket=[]):<br>    bucket.append(item)<br>    return bucket<br>print(add_item_buggy(&quot;a&quot;))<br>print(add_item_buggy(&quot;b&quot;))          # surprise<br>print(add_item_buggy.__defaults__)  # the default lives on the function object<br>def add_item(item, bucket=None):<br>    if bucket is None:<br>        bucket = []                 # a fresh list on every call<br>    bucket.append(item)<br>    return bucket<br>print(add_item(&quot;a&quot;))<br>print(add_item(&quot;b&quot;))</pre><p>Output:</p><pre>[&#39;a&#39;]<br>[&#39;a&#39;, &#39;b&#39;]<br>([&#39;a&#39;, &#39;b&#39;],)<br>[&#39;a&#39;]<br>[&#39;b&#39;]</pre><p>The empty list is created when Python executes the def statement, stored in the function&#39;s __defaults__, and then shared by every call that does not pass bucket. The fix is the None sentinel pattern recommended by the official FAQ.</p><p>If None is a meaningful value for the parameter, create a private sentinel instead: _MISSING = object(), then check if bucket is _MISSING. This is one of the legitimate uses of is.</p><h3>8. Immutable does not mean “deeply frozen”</h3><p>A tuple is immutable: you cannot add, remove or replace its items. But a tuple stores <strong>references</strong>, and the objects it refers to can still be mutable. The language reference covers this case: the tuple’s value changes when the inner object changes, yet the tuple is still immutable because the collection of objects it contains cannot change.</p><pre>config = (&quot;prod&quot;, [&quot;eu-west-1&quot;])<br>config[1].append(&quot;eu-central-1&quot;)     # the tuple holds a reference to a mutable list<br>print(config)<br>try:<br>    hash(config)<br>except TypeError as e:<br>    print(&quot;TypeError:&quot;, e)<br>print(hash((&quot;prod&quot;, &quot;eu-west-1&quot;)) == hash((&quot;prod&quot;, &quot;eu-west-1&quot;)))<br>t = (1, 2, [30, 40])<br>try:<br>    t[2] += [50]<br>except TypeError as e:<br>    print(&quot;TypeError:&quot;, e)<br>print(t)                             # ...and yet the list changed</pre><p>Output:</p><pre>(&#39;prod&#39;, [&#39;eu-west-1&#39;, &#39;eu-central-1&#39;])<br>TypeError: unhashable type: &#39;list&#39;<br>True<br>TypeError: &#39;tuple&#39; object does not support item assignment<br>(1, 2, [30, 40, 50])</pre><p>Two consequences:</p><ul><li><strong>Hashability depends on the contents.</strong> A tuple is hashable only if everything inside it is hashable. That is why a tuple of strings can be a dict key but a tuple containing a list cannot.</li><li><strong>t[2] += [50] both fails and succeeds.</strong> The bytecode shows why. Python loads t[2] (the list), runs the in-place +=, which mutates the list successfully, and <em>then</em> tries to store the result back with t[2] = .... That final STORE_SUBSCR step raises TypeError because tuples do not support item assignment. The mutation already happened.</li></ul><pre>BINARY_SUBSCR        # load t[2], the list<br>BINARY_OP (+=)       # list.__iadd__ mutates it in place  -&gt; succeeds<br>STORE_SUBSCR         # t[2] = result                     -&gt; TypeError</pre><p>(Bytecode from dis on CPython 3.13; instruction names vary between versions, but the order of operations is the same.)</p><p>Why do dict keys need to be immutable at all? A dict finds a key by its hash. If a key’s value could change after insertion, its hash would change, and the dict would look for it in the wrong place. Requiring hashable keys prevents that class of bug. Section 3.3.1 of the data model covers the rules for __hash__; we will come back to it when writing our own classes.</p><h3>9. Copies: shallow versus deep</h3><p>Now back to the opening bug.</p><ul><li>A <strong>shallow copy</strong> creates a new outer container and fills it with references to the <strong>same</strong> inner objects. list(x), x[:], x.copy(), dict(d) and copy.copy(x) are all shallow.</li><li>A <strong>deep copy</strong> (copy.deepcopy) recursively copies the inner objects too.</li></ul><pre>import copy<br>team = {&quot;name&quot;: &quot;web&quot;, &quot;members&quot;: [&quot;ana&quot;, &quot;bob&quot;]}<br>shallow = copy.copy(team)            # same as dict(team) or team.copy()<br>deep = copy.deepcopy(team)<br>team[&quot;members&quot;].append(&quot;cem&quot;)<br>print(shallow[&quot;members&quot;])            # shares the inner list<br>print(deep[&quot;members&quot;])               # fully independent<br>print(shallow is team, shallow[&quot;members&quot;] is team[&quot;members&quot;])<br>print(deep[&quot;members&quot;] is team[&quot;members&quot;])</pre><p>Output:</p><pre>[&#39;ana&#39;, &#39;bob&#39;, &#39;cem&#39;]<br>[&#39;ana&#39;, &#39;bob&#39;]<br>False True<br>False</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UwJjln3Z3QPZ6RnldoDNw.png" /></figure><p><em>Figure 1. After </em><em>team[&quot;members&quot;].append(&quot;cem&quot;), the shallow copy is a new dict that still points at the same list. The deep copy has its own list. Drawn from the output of the example above.</em></p><p>Deep copy is not free, and it is not always correct:</p><ul><li>It costs time and memory proportional to the size of the structure.</li><li>It handles cycles correctly. The copy module keeps a memo dict of objects already copied during the current pass, so a structure that refers to itself does not cause infinite recursion.</li><li>Some objects should not be copied at all: open files, sockets, locks, database connections. Classes can control their behavior with __copy__ and __deepcopy__.</li></ul><p>The opening bug, fixed and protected by tests:</p><pre># settings.py<br>import copy<br>DEFAULTS = {&quot;theme&quot;: &quot;light&quot;, &quot;features&quot;: {&quot;beta&quot;: False}}<br>def add_item(item, bucket=None):<br>    &quot;&quot;&quot;Append item to bucket without sharing state between calls.&quot;&quot;&quot;<br>    if bucket is None:<br>        bucket = []<br>    bucket.append(item)<br>    return bucket<br>def build_settings(overrides=None):<br>    &quot;&quot;&quot;Return a settings dict that never mutates DEFAULTS.&quot;&quot;&quot;<br>    settings = copy.deepcopy(DEFAULTS)<br>    if overrides:<br>        for key, value in overrides.items():<br>            if isinstance(value, dict) and isinstance(settings.get(key), dict):<br>                settings[key].update(value)<br>            else:<br>                settings[key] = value<br>    return settings</pre><pre># test_settings.py<br>from settings import DEFAULTS, add_item, build_settings<br>def test_default_bucket_is_not_shared():<br>    assert add_item(&quot;a&quot;) == [&quot;a&quot;]<br>    assert add_item(&quot;b&quot;) == [&quot;b&quot;]          # fails with bucket=[]<br>def test_explicit_bucket_is_mutated_in_place():<br>    bucket = []<br>    result = add_item(&quot;x&quot;, bucket)<br>    assert result is bucket                 # caller&#39;s object, by design<br>def test_overrides_do_not_leak_into_defaults():<br>    s = build_settings({&quot;features&quot;: {&quot;beta&quot;: True}})<br>    assert s[&quot;features&quot;][&quot;beta&quot;] is True<br>    assert DEFAULTS[&quot;features&quot;][&quot;beta&quot;] is False   # fails with a shallow copy<br>def test_each_call_returns_independent_settings():<br>    s1 = build_settings()<br>    s2 = build_settings()<br>    s1[&quot;features&quot;][&quot;beta&quot;] = True<br>    assert s2[&quot;features&quot;][&quot;beta&quot;] is False<br>    assert s1 is not s2</pre><p>Running pytest (9.x, Python 3.13): 4 passed. To check that the tests actually protect against the bug, I replaced copy.deepcopy(DEFAULTS) with the shallow dict(DEFAULTS) and ran them again: test_overrides_do_not_leak_into_defaults and test_each_call_returns_independent_settings failed, as they should. A test you have never seen fail has not proven anything yet.</p><h3>10. Under the hood in CPython</h3><p>Everything above is language semantics. This section is specific to CPython, the reference implementation, and is useful for building intuition rather than something to rely on in code.</p><p>In CPython, every object is a C struct that starts with a common header: a <strong>reference count</strong> and a pointer to the object’s <strong>type</strong>. A Python name is an entry in a namespace (essentially a dict for module and class scopes, and an optimized array for function locals) that holds a pointer to such a struct. That is why assignment is cheap: it copies a pointer and increments a counter.</p><p>Memory is managed by two mechanisms:</p><ol><li><strong>Reference counting.</strong> When an object’s count drops to zero, it is freed immediately.</li><li><strong>A cyclic garbage collector</strong> (the gc module) that periodically finds groups of objects that refer to each other but are no longer reachable, which reference counting alone cannot free.</li></ol><pre>import sys<br>data = [1, 2, 3]<br>alias = data<br>print(sys.getrefcount(data))   # includes the temporary reference from the call<br>del alias                      # removes a NAME, not the object<br>print(sys.getrefcount(data))<br>print(data)</pre><p>Output on CPython 3.13:</p><pre>3<br>2<br>[1, 2, 3]</pre><p>del removes a name binding. It does not delete the object; the object is freed only when nothing refers to it anymore. The exact numbers returned by sys.getrefcount vary between versions and are best treated as illustrative.</p><h3>11. Choosing a strategy: share, copy or freeze</h3><ul><li><strong>Share (aliasing).</strong> Use when: Read-only access, or mutation is the explicit purpose. Cost: None. Risk: Hidden coupling between callers.</li><li><strong>Shallow copy.</strong> Use when: The structure is flat, or inner objects are immutable. Cost: O(n) for the outer container. Risk: Nested mutable objects are still shared.</li><li><strong>Deep copy.</strong> Use when: Nested mutable data must be fully independent. Cost: Proportional to the whole structure. Risk: Slow for large data; wrong for resources like files and connections.</li><li><strong>Immutable structures (</strong><strong>tuple, </strong><strong>frozenset, frozen dataclasses).</strong> Use when: Configuration, keys, values shared across threads or requests. Cost: Creating a new object for every change. Risk: Still shallow if they contain mutable objects.</li></ul><p>A senior-level default: <strong>don’t mutate what you didn’t create</strong>. Functions should take inputs, return new values and leave arguments unchanged, unless mutation is the stated purpose (list.sort() versus sorted() is the standard library&#39;s own example of naming this difference). Prefer immutable data for anything shared, and reach for deepcopy deliberately, not as a reflex.</p><h3>12. Applying it to a utility library</h3><p>Utility libraries are exactly where these rules matter most, because callers pass in their own lists and dicts. For every helper, the API should answer two questions explicitly: does it mutate its input, and does it return a new object or a view of the original? The tests in section 9 are the template: one test that proves the documented behavior, and one that would fail if a shallow copy or shared default slipped in.</p><h3>Exercises</h3><p><strong>Level 1 — Understanding.</strong> Without running it, predict the output, then run it and explain any difference:</p><pre>a = [[0] * 3] * 3<br>a[0][0] = 1<br>print(a)</pre><p><em>Acceptance:</em> a one-paragraph explanation that uses the words “reference” and “same object”. Then write a version that creates three independent rows.</p><p><strong>Level 2 — Implementation.</strong> Write deep_merge(base: dict, override: dict) -&gt; dict that returns a new dict where nested dicts are merged recursively. <em>Acceptance:</em> neither input is modified (prove it with tests), nested keys from both inputs survive, and the function works with three levels of nesting.</p><p><strong>Level 3 — Engineering judgment.</strong> A web service loads a 50 MB configuration once at startup and every request needs to read it, while a few requests need a modified version. Compare deep copying per request, shallow copying, and an immutable structure. <em>Acceptance:</em> a short written decision with the trade-offs in memory, latency and safety.</p><p><strong>Level 4 — Challenge.</strong> Create a structure that contains itself (for example, a list that appends itself) and deep copy it. Explain, with reference to the memo argument, why it does not recurse forever. Then write a class whose __deepcopy__ deliberately shares one attribute (for example, a logger) while copying the rest, and test it.</p><h3>Knowledge check</h3><ol><li>What three properties does every Python object have, and which of them can change?</li><li>Why is x is 257 a bad test even if it works on your machine?</li><li>A function receives a list and does items = items + [&quot;x&quot;]. Does the caller see &quot;x&quot;? What if it does items += [&quot;x&quot;]?</li><li>Why can a tuple be a dict key in one case but not another?</li><li>Explain why t[2] += [50] raises an error but still changes t.</li><li>A teammate fixes a “settings leaking between users” bug by replacing DEFAULTS.copy() with dict(DEFAULTS). Will it work?</li><li>Interview question: “Is Python pass-by-value or pass-by-reference?” Answer in three sentences.</li></ol><h4>Answers</h4><ol><li>Identity, type and value. Identity and type never change; the value can change only for mutable types.</li><li>Because identity of equal immutable values is an implementation detail. CPython 3.13 caches only small ints, other versions use different ranges, and other implementations may behave differently. Use ==.</li><li>With items = items + [&quot;x&quot;], no: a new list is created and only the local name is rebound. With items += [&quot;x&quot;], yes: list.__iadd__ mutates the caller&#39;s list in place.</li><li>A tuple is hashable only if all of its items are hashable. (&quot;a&quot;, 1) works; (&quot;a&quot;, [1]) raises TypeError: unhashable type: &#39;list&#39;.</li><li>The in-place addition mutates the list first and succeeds; Python then tries to assign the result back into the tuple slot, and that assignment fails because tuples do not support item assignment.</li><li>No. Both are shallow copies. Nested dicts are still shared. It needs a deep copy, or better, defaults built fresh per call or stored as immutable data.</li><li>Neither, strictly. Python passes references to objects by assignment (“call by sharing”): the function can mutate a mutable argument, but rebinding the parameter never affects the caller’s variable. To give the caller a new object, the function returns it.</li></ol><h3>Summary and mastery criteria</h3><ul><li>A name is a label bound to an object. Assignment and argument passing never copy.</li><li>== compares values; is compares identity and belongs with singletons and sentinels.</li><li>Mutability belongs to the type. Immutable containers can still hold mutable objects.</li><li>+= mutates when the type supports it and rebinds otherwise.</li><li>Default argument values are evaluated once.</li><li>Shallow copies share inner objects; deep copies don’t, at a cost.</li></ul><p>You have this topic when you can: predict the output of every example above before running it; explain the tuple += behavior from the bytecode; write the deep_merge exercise with tests that fail on a shallow implementation; and answer question 7 clearly in under a minute.</p><h3>References</h3><ul><li>Python Language Reference, <a href="https://docs.python.org/3/reference/datamodel.html#objects-values-and-types">3.1 Objects, values and types</a> — the definitions of identity, type, value and mutability used throughout this article.</li><li>Python Language Reference, <a href="https://docs.python.org/3/reference/compound_stmts.html#function-definitions">Function definitions</a> — default values are evaluated once.</li><li>Python Language Reference, <a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements">Augmented assignment statements</a> — in-place operation “when possible”.</li><li>Python FAQ, <a href="https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x">Why did changing list ‘y’ also change list ‘x’?</a> and <a href="https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference">How do I write a function with output parameters?</a></li><li>Python Glossary, <a href="https://docs.python.org/3/glossary.html#term-hashable">hashable</a>.</li><li>Python Library Reference, <a href="https://docs.python.org/3/library/copy.html">copy — Shallow and deep copy operations</a>.</li><li>CPython C API, <a href="https://docs.python.org/3.13/c-api/long.html">Integer Objects (3.13)</a> — the small integer cache, documented as an implementation detail.</li><li>Luciano Ramalho, <em>Fluent Python</em>, 2nd Edition, Chapter 6, “Object References, Mutability, and Recycling” — the best next read on this topic.</li></ul><p><em>Next in this series: inside </em><em>list, </em><em>dict, </em><em>set and </em><em>tuple — how they are built and what their operations really cost.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6711c12b05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming LLM Responses in React: What Actually Makes It Feel Fast]]></title>
            <link>https://medium.com/@hajaghahasanli/streaming-llm-responses-in-react-what-actually-makes-it-feel-fast-0bd6517952f5?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd6517952f5</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-engineer]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 11:23:05 GMT</pubDate>
            <atom:updated>2026-10-20T11:23:05.887Z</atom:updated>
            <content:encoded><![CDATA[<h4>The model sets the latency. The interface decides how it feels.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A90Qz1eWuicIRus2qRrtKw.png" /></figure><p>An LLM response that takes eight seconds can feel instant or broken. Same model, same prompt, same eight seconds. The difference is what the user sees in the first second.</p><p>If the interface waits for the full response and then renders it, the user stares at a spinner for eight seconds and starts wondering whether something failed. If it streams, the first words show up in a few hundred milliseconds and the user is already reading while the rest arrives.</p><p>Nothing about the model changed. The frontend did.</p><p>I spend a lot of my time building streaming interfaces for AI products, and the most useful lesson has been this: turning on streaming is the easy part. Making streaming feel good is a set of small rendering, parsing and lifecycle problems that are easy to miss until real users hit them. This article walks through the ones that matter most.</p><h3>1. Measure the right number: time to first token</h3><p>Total response time is what the backend sees. Users experience something else.</p><p><strong>Time to first token (TTFT)</strong> is the time from sending the request to the first token arriving. For the user, the more useful variant is time to first <em>meaningful</em> token: the first visible word, not a whitespace chunk or a protocol frame.</p><p>If you only track total latency, you can make the product feel slower while your dashboard says nothing changed. Track both:</p><ul><li><strong>TTFT</strong> tells you how quickly the product feels alive.</li><li><strong>Total time</strong> tells you how long the user waits for the complete answer.</li><li><strong>Render cost per token</strong> tells you whether your UI keeps up with the stream.</li></ul><p>Streaming itself usually travels over <strong>Server-Sent Events (SSE)</strong>, which most LLM APIs use, or <strong>WebSockets</strong> when you need two-way communication. The transport matters less than what you do with each chunk once it arrives.</p><h3>2. Streaming is a rendering problem</h3><p>The naive implementation looks like this:</p><pre>onToken((token) =&gt; {<br>  setText((prev) =&gt; prev + token);<br>});</pre><p>It works in a demo. On a long answer it starts to stutter, for two reasons.</p><p>First, tokens can arrive faster than the screen refreshes, so you end up scheduling more renders than the user can ever see.</p><p>Second, and more expensive: each render usually re-parses the <strong>entire</strong> response so far, because it is Markdown. A 2,000-token answer rendered token by token means parsing a growing string thousands of times. The work grows roughly quadratically with response length, which is exactly why long answers get slower as they go.</p><p>The fix is to decouple receiving from rendering. Collect tokens in a buffer and flush at most once per animation frame:</p><pre>function useStreamBuffer() {<br>  const bufferRef = useRef(&quot;&quot;);<br>  const frameRef = useRef&lt;number | null&gt;(null);<br>  const [text, setText] = useState(&quot;&quot;);<br>  const push = useCallback((token: string) =&gt; {<br>    bufferRef.current += token;<br>    if (frameRef.current === null) {<br>      frameRef.current = requestAnimationFrame(() =&gt; {<br>        frameRef.current = null;<br>        setText(bufferRef.current);<br>      });<br>    }<br>  }, []);<br>  useEffect(() =&gt; () =&gt; {<br>    if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);<br>  }, []);<br>  return { text, push };<br>}</pre><p>requestAnimationFrame ties your render rate to the display’s refresh rate. However many tokens arrive, the UI renders once per frame at most.</p><p>Two follow-ups make this hold up in production:</p><ul><li><strong>Memoize completed blocks.</strong> Split the response into blocks (paragraphs, code blocks, list items) and memoize the ones that are finished. Only the last, still-growing block needs to re-render.</li><li><strong>Keep the stream out of global state.</strong> Pushing every flush through a global store re-renders everything subscribed to it. Keep the streaming text local to the message component and commit the final result to the store when the stream ends.</li></ul><h3>3. Markdown breaks mid-stream</h3><p>LLM output is almost always Markdown, and a stream is almost always incomplete Markdown.</p><p>Halfway through a response you might have:</p><pre>Here is the fix:<br>```ts<br>const result = await</pre><p>The code fence is open. A standard Markdown parser does not know the block will close in a moment, so it may render everything after the fence as code, or render the fence characters as plain text. When the closing fence arrives, the layout jumps. Tables, nested lists and bold text that has opened but not closed cause the same flicker.</p><p>There are two reasonable strategies:</p><ul><li><strong>Close it temporarily.</strong> Before parsing, detect unclosed constructs (an odd number of code fences, an unterminated **) and close them in a copy of the string used only for rendering. The user sees a code block that grows, rather than a layout that flips.</li><li><strong>Hold it back.</strong> Render all completed blocks and keep the unfinished one as plain text, or hidden, until it closes. This is simpler and very stable, at the cost of a slightly delayed last block.</li></ul><p>You do not have to build this from scratch. Libraries such as Vercel’s <a href="https://streamdown.ai/docs">Streamdown</a> are designed specifically for rendering incomplete Markdown during streaming. Whatever you use, test it with long code blocks and tables, because that is where users notice.</p><h3>4. Structured outputs and streaming pull in opposite directions</h3><p>Many AI features need structured data, not prose. A search assistant might turn “3-bedroom apartment in Baku under 150k” into:</p><pre>{ &quot;city&quot;: &quot;Baku&quot;, &quot;rooms&quot;: 3, &quot;maxPrice&quot;: 150000 }</pre><p>JSON is only valid when it is complete. Mid-stream you have { &quot;city&quot;: &quot;Bak, and JSON.parse throws.</p><p>You have to choose, deliberately:</p><ul><li><strong>Stream partial JSON and parse it tolerantly.</strong> A tolerant parser closes open strings, arrays and objects to produce the best current guess. Several AI SDKs ship partial-object streaming for this. It is great for UI that fills in progressively, such as form fields or filter chips. The risk is that intermediate values are wrong (“Bak” is not a city), so never trigger side effects such as API calls or navigation from a partial object.</li><li><strong>Separate the two concerns.</strong> Stream the human-readable explanation to the user, and deliver the structured part at the end, validated against a schema (with Zod, for example) before anything acts on it. It is less flashy and much easier to reason about.</li></ul><p>The mistake is drifting into a mix of both without deciding, where partially parsed data leaks into application logic.</p><h3>5. Auto-scroll is a feature</h3><p>Chat interfaces scroll to the bottom as new text arrives. That is right until the user scrolls up to reread something, and the next token yanks them back down. Few things make a good answer feel more irritating.</p><p>The expected behavior is “stick to bottom”:</p><ul><li>If the user is at the bottom, follow the stream.</li><li>If the user scrolls up, stop following and show a small “jump to latest” button.</li><li>When the user returns to the bottom, resume following.</li></ul><pre>const isNearBottom = (el: HTMLElement, threshold = 48) =&gt;<br>  el.scrollHeight - el.scrollTop - el.clientHeight &lt; threshold;</pre><p>Check this before each flush, not after, because after the flush the content has already grown. An IntersectionObserver on an invisible sentinel element at the end of the list is a clean alternative that avoids scroll-event handling entirely.</p><h3>6. “Stop” has to actually stop</h3><p>Every streaming UI has a stop button. In many implementations it only stops <em>rendering</em>: the UI hides further tokens while the HTTP request stays open, the model keeps generating, and you keep paying for tokens nobody will read.</p><p>Cancel the request itself:</p><pre>const controller = new AbortController();<br>fetch(&quot;/api/chat&quot;, {<br>  method: &quot;POST&quot;,<br>  body: JSON.stringify(payload),<br>  signal: controller.signal,<br>});<br>// Stop button<br>controller.abort();</pre><p>That is only half of it. The backend has to notice the client disconnected and cancel the upstream model call. Otherwise the frontend stopped, but the cost did not. This is one of those problems that sits exactly on the boundary between frontend and backend, which is why it is often nobody’s job.</p><p>Also decide what “stopped” means in the UI. Keep the partial answer, mark it as stopped, and make sure the next message does not inherit a half-closed stream.</p><h3>7. The details that separate a demo from a product</h3><p>A few smaller things that show up quickly in real usage:</p><ul><li><strong>Errors mid-stream.</strong> The stream can fail after 300 tokens. Keep what was received, show where it broke and offer a retry, instead of replacing the whole answer with an error.</li><li><strong>Reconnection.</strong> On flaky mobile networks, decide whether a dropped stream resumes or restarts, and make it visible to the user.</li><li><strong>Accessibility.</strong> Screen readers and aria-live regions do not cope well with text that changes 30 times a second. Announce the completed response, or completed sentences, rather than every token.</li><li><strong>Layout shift.</strong> Reserve space for the message container and avoid images or embeds that reflow the page while text is still arriving.</li></ul><h3>The takeaway</h3><p>None of this makes the model smarter. It makes the product feel faster, more stable and more respectful of the user’s time, and for most users that is what quality means.</p><p>If you are building an AI feature, the model is only half of the experience. The other half is a set of very ordinary frontend engineering decisions: when to render, what to parse, who owns the scroll position and what “stop” really does.</p><p>What streaming edge case has cost you the most time? I would like to hear how other teams handle it.</p><p><em>I’m a Lead Frontend Engineer working on AI-powered products with React, TypeScript and Next.js. I write about frontend architecture, AI interfaces and engineering leadership.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd6517952f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Media in the Browser: Screen Capture, Audio Tools, and MediaRecorder Explained]]></title>
            <link>https://medium.com/@hajaghahasanli/creating-media-in-the-browser-screen-capture-audio-tools-and-mediarecorder-explained-fe4e617f7efc?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4e617f7efc</guid>
            <category><![CDATA[screen-capture]]></category>
            <category><![CDATA[mediarecorder]]></category>
            <category><![CDATA[audiotool]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Fri, 23 May 2025 16:11:01 GMT</pubDate>
            <atom:updated>2025-05-23T16:11:01.175Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve watched videos and played audio in the browser, but did you know you can also <strong>record</strong>, <strong>stream</strong>, and <strong>edit</strong> them using just JavaScript? In this post, we’ll explore MediaRecorder, getUserMedia, screen capture, Web Audio API, and real-time media stream handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*VXpNI2lDJ0HfzA1RgG7jEw.png" /></figure><p>Recording a podcast? Streaming your screen? Capturing a voice message?<br> You don’t need native apps or backend services to do this anymore — the browser is powerful enough.</p><p>In this article, we’ll look at how frontend developers can work with <strong>media input</strong>, not just output. That means capturing video/audio, recording it, manipulating it, and even streaming it — all from the client side.</p><p>We’ll explore:</p><ul><li>Capturing webcam or mic input</li><li>Recording screen or tab video</li><li>Saving media recordings</li><li>Processing real-time audio</li><li>Using streams directly in JS</li></ul><h3>Capturing Audio and Video with getUserMedia()</h3><p>Let’s start with the basics: accessing the webcam and microphone.</p><pre>const stream = await navigator.mediaDevices.getUserMedia({<br>  video: true,<br>  audio: true,<br>});<br><br>const videoElement = document.querySelector(&#39;video&#39;);<br>videoElement.srcObject = stream;<br>videoElement.play();</pre><p>This gives you a <strong>live video/audio stream</strong> from the user’s device — no plugins needed.</p><p>Use cases:</p><ul><li>Video calls</li><li>Voice chat</li><li>Previewing before recording</li><li>Real-time visual filters (using &lt;canvas&gt;)</li></ul><h3>Recording Media with MediaRecorder</h3><p>Once you have a media stream (from getUserMedia or screen capture), you can record it using the MediaRecorder API.</p><pre>const chunks = [];<br>const recorder = new MediaRecorder(stream);<br><br>recorder.ondataavailable = (e) =&gt; chunks.push(e.data);<br>recorder.onstop = () =&gt; {<br>  const blob = new Blob(chunks, { type: &#39;video/webm&#39; });<br>  const url = URL.createObjectURL(blob);<br>  downloadRecording(url);<br>};<br><br>recorder.start();<br><br>// Later…<br>recorder.stop();<br><br>function downloadRecording(url) {<br>  const a = document.createElement(&#39;a&#39;);<br>  a.href = url;<br>  a.download = &#39;recording.webm&#39;;<br>  a.click();<br>}</pre><p>This will create a downloadable .webm file recorded from the user’s webcam and mic.</p><h3>Capturing the Screen: getDisplayMedia()</h3><p>Want to record the screen instead of the webcam? Use getDisplayMedia().</p><pre>const stream = await navigator.mediaDevices.getDisplayMedia({<br>  video: true,<br>  audio: true,<br>});</pre><p>This lets users choose to share:</p><ul><li>Their full screen</li><li>A single window</li><li>A specific browser tab</li></ul><p>Combine it with MediaRecorder, and you can record screen tutorials, gameplay, or meetings entirely in-browser.</p><h3>Real-Time Audio Manipulation: Web Audio API</h3><p>The <strong>Web Audio API</strong> lets you build complex audio graphs — think mixing boards, EQs, or effects chains.</p><p>Want to visualize the mic input in real time?</p><pre>const stream = await navigator.mediaDevices.getUserMedia({ audio: true });<br>const ctx = new AudioContext();<br>const source = ctx.createMediaStreamSource(stream);<br>const analyser = ctx.createAnalyser();<br><br>source.connect(analyser);<br><br>const data = new Uint8Array(analyser.frequencyBinCount);<br>function draw() {<br>  requestAnimationFrame(draw);<br>  analyser.getByteFrequencyData(data);<br>  console.log(data); // visualize this on canvas<br>}<br>draw();</pre><p>You can also:</p><ul><li>Apply gain/volume control</li><li>Add filters or delays</li><li>Route audio to speakers or to a file</li><li>Analyze pitch/frequency in real time</li></ul><p>Great for:</p><ul><li>Audio editors</li><li>Music apps</li><li>Podcast tools</li><li>Voice-controlled apps</li></ul><h3>Media Streams as First-Class Citizens</h3><p>Both getUserMedia() and getDisplayMedia() return a <strong>MediaStream</strong> — which is a live, readable stream of audio/video.</p><p>You can:</p><ul><li>Pipe it into MediaRecorder</li><li>Feed it to &lt;video&gt; or &lt;audio&gt;</li><li>Route it into WebRTC for real-time P2P streaming</li><li>Read its tracks and manipulate them individually</li></ul><pre>const audioTrack = stream.getAudioTracks()[0];<br>audioTrack.enabled = false; // mute mic without stopping stream</pre><p>This gives you extremely fine-grained control — like muting, switching inputs, or replacing tracks on the fly during a call.</p><h3>Stream APIs in Plain JavaScript</h3><p>Browser streams go beyond media — you can work with <strong>streaming text, binary data, or files</strong> using ReadableStream, WritableStream, and TransformStream.</p><p>Basic readable stream example:</p><pre>const stream = new ReadableStream({<br>  start(controller) {<br>    controller.enqueue(&#39;Hello, &#39;);<br>    controller.enqueue(&#39;world!&#39;);<br>    controller.close();<br>  }<br>});<br><br>const reader = stream.getReader();<br>reader.read().then(console.log); // { value: &#39;Hello, &#39;, done: false }</pre><p>These low-level primitives are essential for:</p><ul><li>Video/audio transcoding</li><li>Large file handling</li><li>Real-time chunked upload/download</li><li>Building WebTorrent-like systems</li></ul><h3>Use Cases You Can Build Today</h3><ol><li><strong>In-browser screen recorder</strong><br> Use getDisplayMedia() + MediaRecorder to let users record tutorials or meetings.</li><li><strong>Voice memo tool</strong><br> Record mic input and save it to local storage or send it to your backend.</li><li><strong>Live audio visualizer</strong><br> Use Web Audio API to build real-time waveforms or frequency bars.</li><li><strong>Collaborative whiteboard with audio</strong><br> Combine screen share + audio recording + WebRTC for real-time collaboration.</li><li><strong>Drag-and-drop video editor</strong><br> Process media streams, apply filters, trim segments — right in the browser.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4e617f7efc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Data Handling in JavaScript: ArrayBuffers, TypedArrays, Blobs, and Base64]]></title>
            <link>https://medium.com/@hajaghahasanli/binary-data-handling-in-javascript-arraybuffers-typedarrays-blobs-and-base64-a034a7c27a32?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a034a7c27a32</guid>
            <category><![CDATA[array-buffer]]></category>
            <category><![CDATA[base64]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[binary-data]]></category>
            <category><![CDATA[typedarray]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Tue, 20 May 2025 18:11:38 GMT</pubDate>
            <atom:updated>2025-05-20T18:11:38.938Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with binary data might sound like something only low-level systems programmers do. But in modern frontend engineering — from file uploads to WebSockets, image manipulation, and browser-based audio tools — you’ll eventually need to deal with raw bytes.</p><p>Here’s your complete guide to understanding binary data in the browser using <strong>ArrayBuffers</strong>, <strong>TypedArrays</strong>, <strong>Blobs</strong>, and <strong>Base64</strong>. By the end of this post, you’ll be comfortable reading, transforming, and writing raw binary data in real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*V7oAGK9o8twDmeXs.png" /></figure><h3>What is Binary Data?</h3><p>Binary data is the raw form of all data on your computer — just 0s and 1s. Even high-level things like images, text files, and audio are stored and transmitted as binary behind the scenes.</p><p>In frontend development, you typically deal with JSON, strings, and objects. But when working with things like:</p><ul><li>File uploads or downloads</li><li>Media streaming (images, audio, video)</li><li>Custom protocols over WebSocket</li><li>Encoded or compressed content</li><li>Web APIs like WebRTC, WebGL, or FileReader</li></ul><p>…you’ll need to go deeper. That’s where JavaScript’s binary tools come in.</p><h3>ArrayBuffer: Your Binary Container</h3><p>At the heart of binary data handling is ArrayBuffer.</p><p>An ArrayBuffer is a <strong>low-level binary container</strong> — a fixed-length chunk of memory. You can’t directly read/write it — it’s just bytes sitting in memory. To interact with it, you need a <strong>TypedArray</strong> or <strong>DataView</strong>.</p><pre>const buffer = new ArrayBuffer(8); // 8 bytes (64 bits)<br><br>console.log(buffer.byteLength); // 8</pre><p>You now have 8 empty bytes of memory — but what do they mean? To make sense of it, we use a <strong>TypedArray</strong>.</p><h3>What’s the Difference Between an Array and an ArrayBuffer?</h3><p>It’s easy to confuse these two. Let’s clear it up.</p><h4>Regular JavaScript Array</h4><ul><li>Flexible — can hold numbers, strings, objects, etc.</li><li>Dynamic — you can resize it with .push(), .pop(), etc.</li><li>Good for app-level state and logic.</li></ul><pre>const arr = [1, &#39;two&#39;, { key: &#39;value&#39; }];<br><br>arr.push(42); // totally valid</pre><h4>ArrayBuffer</h4><ul><li>Fixed-size chunk of memory</li><li>Holds raw binary data (just bytes)</li><li>Doesn’t “know” what the data means until you interpret it</li></ul><pre>const buffer = new ArrayBuffer(4); // 4 bytes<br>const view = new Uint8Array(buffer);<br>view[0] = 255;</pre><h4>Analogy</h4><p>Think of an Array as a <strong>shopping cart</strong> — you can throw anything in.<br>But ArrayBuffer It&#39;s like a <strong>briefcase with exactly 4 slots</strong>, and each slot only fits a certain type of item.</p><p>Use Array for flexible data structures. Use ArrayBuffer when you need to tightly control binary content, like you would when working with media or network protocols.</p><h3>TypedArray: Making Sense of the Buffer</h3><p>To read/write an ArrayBuffer, you need a TypedArray — a view that interprets the buffer as a specific type.</p><pre>const buffer = new ArrayBuffer(4);<br>const view = new Uint8Array(buffer);<br><br>view[0] = 255;<br>view[1] = 42;<br><br>console.log(view); // Uint8Array(4) [255, 42, 0, 0]</pre><p>Common TypedArrays:</p><ul><li>Uint8Array → 8-bit unsigned ints (0–255)</li><li>Int16Array → 16-bit signed ints</li><li>Float32Array → 32-bit floating-point numbers</li></ul><p>Different TypedArrays allow different interpretations of the same memory, so choose the type based on your use case.</p><h4>Blob: Binary With Metadata</h4><p>A Blob is a high-level representation of binary data with optional type metadata (e.g. text/plain, image/png). You often use it when working with files, uploads, or downloads.</p><pre>const blob = new Blob([&#39;Hello world!&#39;], { type: &#39;text/plain&#39; });<br>const url = URL.createObjectURL(blob);<br>const link = document.createElement(&#39;a&#39;);<br>link.href = url;<br>link.download = &#39;hello.txt&#39;;<br>link.click();</pre><p>This will let the user download a plain text file — no server required.</p><h4>Real-World Example: Reading File Bytes in the Browser</h4><p>Let’s say a user uploads a file, and you want to inspect the binary content:</p><pre>const input = document.querySelector(&#39;input[type=&quot;file&quot;]&#39;);<br><br>input.addEventListener(&#39;change&#39;, async () =&gt; {<br>  const file = input.files[0];<br>  const buffer = await file.arrayBuffer();<br>  const bytes = new Uint8Array(buffer);<br><br>  console.log(&#39;First 10 bytes:&#39;, bytes.slice(0, 10));<br>});</pre><p>This technique is useful for:</p><ul><li>Previewing uploaded files</li><li>Validating file structure or headers</li><li>Parsing binary formats (e.g., custom protocol, compressed data)</li></ul><h4>Converting Between Blob and ArrayBuffer</h4><p>Need to switch between formats?</p><h4>Blob → ArrayBuffer</h4><pre>const buffer = await blob.arrayBuffer();</pre><h4>ArrayBuffer → Blob</h4><pre>const blob = new Blob([buffer], { type: &#39;application/octet-stream&#39; });</pre><p>This back-and-forth is common when uploading processed binary data, or downloading it as a file.</p><h3>Base64 Encoding: Binary as Text</h3><p>Sometimes, you’ll need to convert binary data into a string — for embedding it in HTML, sending over JSON, or uploading via REST.</p><h4>Convert ArrayBuffer to Base64:</h4><pre>function arrayBufferToBase64(buffer) {<br>  const bytes = new Uint8Array(buffer);<br>  let binary = &#39;&#39;;<br>  for (let i = 0; i &lt; bytes.length; i++) {<br>    binary += String.fromCharCode(bytes[i]);<br>  }<br>  return btoa(binary);<br>}</pre><p>Base64 adds about <strong>33% size overhead</strong>, so avoid it for large files unless necessary.</p><h3>When Will You Use This?</h3><p>Binary data handling matters in real frontend work, especially when building:</p><ul><li>File uploaders with previews and validation</li><li>Image editors using &lt;canvas&gt; or WebGL</li><li>Audio tools using Web Audio API and audio buffers</li><li>Real-time systems using WebSocket or WebRTC</li><li>Apps that download or generate files client-side</li><li>Any app dealing with a performance-sensitive data format</li></ul><p>Understanding binary helps you go beyond the DOM and build serious browser-based systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a034a7c27a32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Need Redux for This: The New Underrated Hero]]></title>
            <link>https://medium.com/@hajaghahasanli/you-dont-need-redux-for-this-the-new-underrated-hero-13857bc6c819?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/13857bc6c819</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[jotai]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[state-management-in-react]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Sun, 18 May 2025 07:01:39 GMT</pubDate>
            <atom:updated>2025-05-20T06:07:35.300Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re still reaching for Redux every time you need to share state in a React app, take a breath. It’s 2025, and we have better tools now. Lighter, more expressive, easier-to-use state libraries are not only viable — they’re <em>preferable</em> in most cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*wWfFhZmljjTZAersc4kWFg.png" /></figure><p>Let me walk you through why you probably don’t need Redux anymore, and why <strong>Jotai</strong> might just become your new favorite state management library.</p><h3>Why Redux Feels Heavy in 2025</h3><p>Redux was revolutionary when it first came out. Predictable state, centralized store, time-travel debugging — it was a dream for large-scale apps.</p><p>But here’s the problem today:</p><ul><li>You have to write a lot of boilerplate (actions, reducers, selectors).</li><li>You’re forced into a global mindset, even when you don’t need it.</li><li>It doesn’t feel ergonomic for modern React with hooks and composition.</li></ul><p>React has evolved. And so should our tools.</p><h3>What Do Most Apps Actually Need?</h3><p>Think about your last 3 projects. You probably needed:</p><ul><li>Local component state</li><li>A shared user object or theme mode</li><li>Maybe a search filter or modal visibility flag shared between a few components</li></ul><p>That’s it.</p><p>You don’t need a global reducer with dispatch for that. You need something more <strong>reactive</strong>, <strong>composable</strong>, and <strong>minimal</strong>.</p><h3>The Rise of Simpler Alternatives</h3><p>Today we have tools like:</p><ul><li><strong>React Context + useState/useReducer</strong> (great for very small apps)</li><li><strong>Zustand</strong> (simple, minimal, solid)</li><li><strong>Recoil</strong> (powerful but more complex)</li><li><strong>Jotai</strong> (the underrated hero)</li><li><strong>Valtio</strong>, <strong>Nanostores</strong>, and others</li></ul><p>Let’s focus on Jotai — a hidden gem that gives you atom-based state management without boilerplate or magic.</p><h3>Why Jotai is So Effective</h3><h4>1. Minimal Setup</h4><p>No store, no provider, no configuration — just import and use. It integrates into any React project with almost zero friction.</p><h4>2. Tiny Package Size</h4><p>Jotai is incredibly lightweight.</p><ul><li><strong>Minified + gzipped size:</strong> ~<strong>3.5 KB</strong></li><li>Compare that to:</li><li>Redux + Redux Toolkit + React-Redux: <strong>&gt;20 KB</strong></li><li>Recoil: <strong>~20 KB</strong></li><li>Zustand: ~<strong>1.5 KB</strong> (also minimal, but lacks Jotai’s derived/async atom power)</li></ul><p>If you’re working on performance-sensitive apps or aiming for faster initial load times (especially in SPAs or PWAs), Jotai helps keep your JavaScript payload lean.</p><h4>3. Highly Performant</h4><p>Jotai is built with reactivity in mind. It tracks exactly what each component uses, so updates only trigger <strong>precise re-renders</strong>, not full re-renders of the component tree like with Context.</p><ul><li>Atoms are updated individually</li><li>No need for memoization hacks</li><li>You don’t suffer from “context waterfall” issues</li></ul><p>This makes Jotai feel fast even as your app grows</p><h4>4. Composable</h4><p>You can freely compose atoms, reuse them, or organize them by domain (e.g., user, theme, notifications) — no giant store file or reducer mess</p><h4>5. Derived State with Atoms</h4><p>You can build atoms that <strong>depend on other atoms</strong>. This makes selector-like logic feel natural and declarative.</p><h4>Declaring an Atom</h4><pre>import { atom } from &#39;jotai&#39;;<br><br>const countAtom = atom(0);<br><br>export default countAtom;</pre><p>This atom holds a simple number. It’s global by default — any component that uses it will get a live value.</p><h4>Using the Atom in a Component</h4><pre>import { useAtom } from &#39;jotai&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useAtom(countAtom);<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      Count: {count}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>No useReducer, no action constants, no dispatch — just a value and a setter, just like useState. But shared.</p><h4>6. Async Support is Built In</h4><p>You can create atoms that fetch data asynchronously:</p><pre>const userAtom = atom(async () =&gt; {<br>  const res = await fetch(&#39;/api/me&#39;);<br>  return res.json();<br>});</pre><p>No need to wrap this in React Query if your use case is simple. Jotai handles the state and loading.</p><h3>Sharing State Between Components</h3><p>The beauty of Jotai is that it makes <strong>shared state</strong> feel like <strong>local state</strong>. You can use the same atom in multiple components without any special wiring.</p><pre>function Display() {<br>  const [count] = useAtom(countAtom);<br>  return &lt;h2&gt;Current Count: {count}&lt;/h2&gt;;<br>}<br><br>function Increment() {<br>  const [, setCount] = useAtom(countAtom);<br>  return &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;+&lt;/button&gt;;<br>}</pre><p>Whether these components are siblings or live in different parts of your app, they stay in sync through the atom.</p><h3>What I Personally Love About Jotai</h3><p>I’ve migrated multiple apps from Redux or even Zustand to Jotai, and the codebase always feels cleaner.</p><ul><li>Less friction to write new features</li><li>Easy to test, isolate, and reset atoms</li><li>Readable state logic — junior developers “get it” instantly</li></ul><p>Jotai gives me the benefits of a global store without the commitment of maintaining one. It fits React’s mental model perfectly: <strong>functional, declarative, and composable</strong>.</p><p>Jotai Docs: <a href="https://jotai.org/docs">https://jotai.org/docs</a></p><blockquote><em>Be sure to applaud to make it even more spectacular 👏🏿!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13857bc6c819" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Refresh Tokens Actually Matter: A Developer-Friendly Guide]]></title>
            <link>https://medium.com/@hajaghahasanli/why-refresh-tokens-actually-matter-a-developer-friendly-guide-6b32cb267103?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b32cb267103</guid>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[jwt-auth]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Fri, 16 May 2025 07:32:33 GMT</pubDate>
            <atom:updated>2025-05-16T07:35:51.271Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building an authentication system and your team is saying: <em>“Why do we even need refresh tokens? If someone steals the access token, they can just steal the refresh token too…”</em> — This article is for you.</p><p>Let’s look why refresh tokens are useful and essential for modern web app security and how to implement them correctly.</p><h3>Access Token vs Refresh Token — What’s the Difference?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WNgmKuPO0gNq3NE4XCagA.png" /><figcaption>Access Token vs Refresh Token — What’s the Difference?</figcaption></figure><h3>Real Talk: “If Someone Steals the Access Token, Won’t They Steal the Refresh Token Too?”</h3><p>This is a common misunderstanding. Here’s the key idea:<br>Access tokens are usually exposed to more risk than refresh tokens.</p><p><strong>Why?</strong></p><ul><li>Access tokens are often stored in localStorage or memory — easy targets for XSS (Cross-Site Scripting) attacks.</li><li>Refresh tokens should only be stored in HttpOnly cookies, which cannot be accessed via JavaScript, even if an attacker injects malicious code.</li></ul><p><strong>So if implemented correctly:</strong></p><ul><li>An attacker might steal the access token.</li><li>But they won’t get the refresh token.</li><li>That means they can’t renew the session — the damage is limited.</li></ul><h3>Example: A Login Flow with Refresh Tokens</h3><ol><li>User logs in → receives:</li></ol><ul><li>Access token (e.g., 15 min)</li><li>Refresh token (e.g., 7 days)</li></ul><p>2. Access token is stored in memory or localStorage.</p><p>3. The refresh token is stored securely as an HTTP-only secure Cookie.</p><p>4. Every time the access token expires:</p><ul><li>Frontend sends the refresh token (automatically via cookie).</li><li>Backend checks it and returns a new access token.</li><li>(Optionally rotates refresh token for security)</li></ul><p><strong>Important note</strong>: If stored in a cookie, the refresh token is sent automatically with requests to the same domain. You <strong>don’t need to send it manually</strong> from the frontend.</p><h3>What Happens If You Don’t Use Refresh Tokens?</h3><p>Let’s say you issue a long-lived access token instead (e.g., 7 days). That means:</p><ul><li>If someone steals the token, they have full access for a week.</li><li>There’s no way to revoke or rotate it unless you maintain a token blacklist.</li><li>Logging the user out becomes much harder.</li></ul><p>Using short-lived access + long-lived refresh tokens gives you control.</p><h3>Can We Renew the Token Using Only the Access Token?</h3><p>Sometimes developers suggest that we can renew tokens using just the access token itself. This might be true in very specific systems (like self-contained JWTs with embedded metadata or token extension endpoints), <strong>but it’s generally not recommended for security reasons</strong>.</p><p><strong>Here’s why:</strong></p><ul><li>The access token is not designed to prove identity after expiration.</li><li>If you allow expired access tokens to be reused for renewal, you risk granting new tokens to attackers who may have stolen them.</li><li>Refresh tokens are meant to act as a secure second layer to prevent such abuse.</li></ul><h3>What is a “self-contained JWT with embedded metadata”?</h3><p>A self-contained JWT (JSON Web Token) is a token that includes all the information needed to authorize the user, encoded directly inside the token itself. It doesn’t require a lookup in the database on every request.</p><p>Example of a decoded JWT payload:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;iat&quot;: 1715790000,<br>  &quot;exp&quot;: 1715793600<br>}</pre><ul><li>sub: subject (usually user ID)</li><li>exp: expiration time</li><li>iat: issued at</li><li>Other claims: role, permissions, email, etc.</li></ul><p>The server validates the signature using a secret or public key, and if it’s valid and not expired, it trusts the contents.</p><h3>How could this be used to “renew” an access token?</h3><p>Some systems try to embed enough metadata in the access token (like refresh time, original session ID, or device ID) so that the access token can act like a refresh token. This might involve:</p><ol><li>The frontend sends the (possibly expired) token to a special /token/extend endpoint.</li><li>The backend verifies the signature and custom metadata (e.g., “was this token created less than 30 minutes ago?”).</li><li>If safe, a new token is issued.</li></ol><p>This pattern avoids storing refresh tokens, but it has serious trade-offs.</p><h3>Why is this risky or discouraged?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_pR9zFoMaBBl6teP-89wA.png" /><figcaption>Why is this risky or discouraged?</figcaption></figure><p>In contrast, a refresh token:</p><ul><li>Is stored securely (e.g., HttpOnly cookie).</li><li>Has a known lifetime and can be rotated.</li><li>Can be individually revoked, tracked, and logged.</li></ul><h3>Why do some systems use token-extension endpoints anyway?</h3><ul><li>Stateless microservices that want to avoid session storage.</li><li>Systems where user sessions are very short-lived and revocation isn’t a concern.</li><li>Internal applications where risk is lower and control is tighter.</li></ul><p>But in most public-facing applications (e.g., SPAs, mobile apps), refresh tokens are far more secure and give you much better session control and risk mitigation</p><h3>Benefits of Refresh Tokens</h3><p><strong>Security:</strong></p><ul><li>Keeps access tokens short-lived — smaller attack window if stolen.</li><li>Refresh tokens are less exposed and can be tracked/revoked if abused.</li></ul><p><strong>User Experience:</strong></p><ul><li>Seamless sessions for users.</li><li>They don’t get logged out every 15 minutes.</li></ul><p><strong>Better Session Management:</strong></p><ul><li>You can detect unusual refresh token usage (e.g., IP/device change).</li><li>Enables logout from all devices or specific sessions.</li></ul><p><strong>Token Rotation:</strong></p><ul><li>You can rotate refresh tokens with each use, invalidating older ones.</li><li>This makes token theft detection and mitigation more powerful.</li></ul><h3>Best Practices When Using Refresh Tokens</h3><ol><li><strong>Store refresh token in HttpOnly, Secure cookies: </strong>Avoid localStorage or JS-accessible storage.</li><li><strong>Use short expiration for access tokens: </strong>Keep them valid for 15–60 minutes max.</li><li><strong>Rotate refresh tokens: </strong>When a refresh token is used, replace it with a new one.</li><li><strong>Detect anomalies: </strong>Monitor usage patterns: sudden IP/device changes, rapid reuses.</li><li><strong>Allow revocation: </strong>Provide users and admins the ability to revoke tokens when needed</li></ol><h3>Simple Analogy: Hotel Keycards</h3><p>Imagine you stay at a hotel:</p><ul><li>The access token is your room keycard — it works for a limited time.</li><li>The refresh token is like a reception-issued pass that lets you get a new keycard when it expires.</li></ul><p>If someone steals your keycard, they can enter your room — but only until it expires. They can’t get another key without your refresh pass (which stays behind the desk).</p><blockquote>Be sure to applaud to make it even more spectacular!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b32cb267103" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GIT and TFS in Context:]]></title>
            <link>https://medium.com/@hajaghahasanli/understanding-git-and-tfs-in-context-a43063569554?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43063569554</guid>
            <category><![CDATA[tf]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[version-control-with-git]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 12:15:30 GMT</pubDate>
            <atom:updated>2025-01-23T13:10:49.678Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Key Features, Pros, and Cons of Two Leading Version Control</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*OqESsn72gU8E6D6H.png" /><figcaption>GIT VS TFS</figcaption></figure><p>GIT is one of the most popular version control systems used worldwide, especially for managing source code. It enables developers to collaborate effectively, even in large teams.</p><p><strong>Key Features of GIT</strong></p><ul><li><strong>Decentralized Nature</strong>: Every developer has a complete copy of the repository, allowing offline work.</li><li><strong>Branching and Merging</strong>: GIT’s branching model is highly flexible, enabling experimentation and collaboration without affecting the main codebase.</li><li><strong>Integration Capabilities</strong>: Works seamlessly with tools like GitHub, GitLab, and Bitbucket, and integrates well into DevOps pipelines.</li></ul><p><strong>Pros</strong></p><ol><li><strong>Rich Learning Resources</strong>: GIT is well-documented with a plethora of online tutorials and courses.</li><li><strong>Offline Work</strong>: Developers can work offline since local repositories contain all project history.</li><li><strong>Cost-Effective</strong>: Free to use with private repository options available within subscription limits.</li><li><strong>Scalability</strong>: Ideal for teams of all sizes; it supports complex workflows effectively.</li></ol><p><strong>Cons</strong></p><ol><li><strong>Conflict Resolution</strong>: Simultaneous editing of the same file by multiple developers can lead to merge conflicts, which need manual resolution.</li><li><strong>Cost of On-Prem Solutions</strong>: Setting up and maintaining on-prem GIT servers can become costly over time.</li></ol><h4>TFS: A Centralized Version Control System</h4><p>Team Foundation Server (TFS) is another version control solution, now often part of Azure DevOps, that focuses on a centralized model.</p><p><strong>Key Features of TFS</strong></p><ul><li><strong>Centralized Nature</strong>: A single, server-hosted repository that all developers work from, ensuring tighter control over file access.</li><li><strong>File Locking</strong>: Prevents multiple developers from editing the same file simultaneously, reducing merge conflicts.</li><li><strong>Integration with Microsoft Ecosystem</strong>: Excellent integration with tools like Office 365, Active Directory, and Azure services.</li></ul><p><strong>Pros</strong></p><ol><li><strong>Conflict Prevention</strong>: Developers cannot open or edit files already being worked on, avoiding conflicts upfront.</li><li><strong>On-Prem Flexibility</strong>: Easy setup for on-prem environments, especially for organizations already using Microsoft solutions.</li><li><strong>Free Access</strong>: Included in Azure DevOps with limits on the free tier, making it a cost-effective choice for smaller teams.</li></ol><p><strong>Cons</strong></p><ol><li><strong>Online Dependency</strong>: Requires constant connectivity to the server, which can be restrictive.</li><li><strong>Buggy Integration</strong>: Occasionally faces reliability issues, particularly when resolving file or folder conflicts.</li></ol><h3>Comparison of GIT vs. TFS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45CdDZ-0u8ldrU9CXIETbg.png" /></figure><p>I’ll break down the comparison between Git and TFS (Team Foundation Server) in a friendly, easy-to-understand way:</p><p>🌍 Nature<br>- Git: Think of it like a team of independent superheroes. Each developer has a full copy of the project, working freely anywhere.<br>- TFS: More like a strict office where everything happens in one central location. You need to be connected to the main system to work.</p><p>💻 Offline Work<br>- Git: You’re a digital nomad! Work from a coffee shop, airplane, or remote island. Your entire project history travels with you.<br>- TFS: Nope, you need an internet connection. It’s like being chained to the office Wi-Fi.</p><p>🤝 Conflict Resolution<br>- Git: Manual merging is like negotiating between two stubborn friends. “Your code goes here, my code goes there.”<br>- TFS: Prevents conflicts by locking files. Imagine a librarian saying, “Only one person can edit this book at a time!”</p><p>🚀 Ease of Integration<br>- Git: Plays well with DevOps tools. It’s the social butterfly of version control systems.<br>- TFS: Best friends with Microsoft tools. If you’re in the Microsoft ecosystem, it’s your perfect match. Works seamlessly with Office 365</p><p>💰 Cost<br>- Git: Free, with paid options for private repositories. It’s like having a budget-friendly Swiss Army knife.<br>- TFS: Free via Azure DevOps. Affordable for smaller teams. Microsoft’s way of saying, “Come join our cool club!”</p><p>📚 Learning Curve<br>- Git: Moderate challenge. Like learning to ride a bicycle — tricky at first, but liberating once you get it.<br>- TFS: Easier for beginners. Think of it as training wheels for version control.</p><p>📈 Scalability<br>- Git: Excellent for large teams. Imagine a massive, well-coordinated flash mob of developers.<br>- TFS: Better for smaller teams. More like a tight-knit startup where everyone knows each other. Locks files to prevent simultaneous editing</p><p>Would you like me to elaborate on any of these points?</p><h3>Choosing the Right Tool</h3><p>Use <strong>GIT</strong> if:</p><ul><li>Your team is large and distributed.</li><li>Offline work is essential.</li><li>You need strong DevOps and CI/CD integration.</li></ul><p>Use <strong>TFS</strong> if:</p><ul><li>Your organization heavily relies on the Microsoft ecosystem.</li><li>You need strict file locking to prevent conflicts.</li><li>Your team works in a centralized, always-online setup.</li></ul><blockquote>By weighing these factors, you can select the version control system that best aligns with your project’s needs and team structure.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43063569554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Server-Side Rendering (SSR) Security Benefits]]></title>
            <link>https://medium.com/@hajaghahasanli/deep-dive-into-server-side-rendering-ssr-security-benefits-a5b7208d8d5d?source=rss-d7911bb64fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b7208d8d5d</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <dc:creator><![CDATA[Hajagha Hasanli]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 17:51:26 GMT</pubDate>
            <atom:updated>2024-08-04T17:55:55.148Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the security implications of server-side rendering (SSR) versus client-side rendering is crucial for developing secure web applications. This expanded guide includes detailed examples of. how SSR enhances security in different scenarios.</p><h3>Expanded Security Enhancements with SSR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oPUt2nHDzLtNzxbNutpB6Q.gif" /><figcaption>security</figcaption></figure><h4>1. Protecting Against Data Exposure</h4><h4>Client-Side Exposure:</h4><p>Imagine a web application that dynamically loads user data using JavaScript:</p><pre>// Client-side JavaScript<br>fetch(&#39;https://api.example.com/userdata&#39;, {<br>  headers: { &#39;Authorization&#39;: &#39;Bearer clientSideTokenExposed&#39; }<br>})<br>.then(response =&gt; response.json())<br>.then(userData =&gt; {<br>  document.getElementById(&#39;welcome&#39;).innerText = `Welcome, ${userData.name}!`;<br>});</pre><p>This script exposes the authorization token in the client-side code, risking token theft through XSS attacks or simple browser inspection.</p><h4>SSR Safeguard:</h4><p>Here’s how you might handle this securely with SSR:</p><pre>// Server-side JavaScript using Express and Node.js<br>app.get(&#39;/dashboard&#39;, (req, res) =&gt; {<br>  const userToken = &#39;secureServerSideToken&#39;;<br>  fetch(&#39;https://api.example.com/userdata&#39;, {<br>    headers: { &#39;Authorization&#39;: `Bearer ${userToken}` }<br>  })<br>  .then(response =&gt; response.json())<br>  .then(userData =&gt; {<br>    res.render(&#39;dashboard&#39;, { welcomeMessage: `Welcome, ${userData.name}!` });<br>  });<br>});</pre><p>In this approach, the authorization token is stored and used server-side, never exposed to the client.</p><h4>2. Mitigating XSS by Encoding User Inputs</h4><h4>Client-Side XSS Risk:</h4><p>Consider a blog platform where comments are dynamically inserted into the page:</p><pre>// Client-side JavaScript vulnerable to XSS<br>const userComment = &#39;&lt;script&gt;stealCookies()&lt;/script&gt;&#39;; // Malicious input<br>document.getElementById(&#39;comments&#39;).innerHTML += userComment;</pre><p>This code snippet naively injects user content directly into the HTML, posing a severe XSS risk.</p><h4>SSR Prevention Strategy:</h4><p>Using SSR, we can encode and safely display user-generated content:</p><pre>// Server-side JavaScript with Node.js<br>app.post(&#39;/submit-comment&#39;, (req, res) =&gt; {<br>  let userComment = encodeHTML(req.body.comment);<br>  // Save and then render the comment safely<br>  saveComment(userComment);<br>  res.redirect(&#39;/comments&#39;);<br>});<br><br>function encodeHTML(str){<br>    return str.replace(/&amp;/g, &#39;&amp;amp;&#39;).replace(/&lt;/g, &#39;&amp;lt;&#39;).replace(/&gt;/g, &#39;&amp;gt;&#39;).replace(/&quot;/g, &#39;&amp;quot;&#39;);<br>}</pre><p>This server-side function ensures that any special characters in comments are encoded, preventing them from being interpreted as HTML or script.</p><h4>3. Controlling Cache Policies</h4><h4>Improper Client-Side Caching:</h4><p>When sensitive data is cached in the client’s browser, it can lead to unauthorized access:</p><pre>// Client-side JavaScript that might cache sensitive data<br>fetch(&#39;https://api.example.com/private-data&#39;)<br>.then(response =&gt; response.json())<br>.then(data =&gt; {<br>  sessionStorage.setItem(&#39;privateData&#39;, JSON.stringify(data));<br>});</pre><p>This data, stored in sessionStorage, could be accessed by other scripts or persist inappropriately.</p><h4>SSR Cache-Control:</h4><p>With SSR, we can set appropriate cache-control headers to prevent sensitive data from being stored:</p><pre>// Server-side JavaScript with Node.js<br>app.get(&#39;/private-data&#39;, (req, res) =&gt; {<br>  res.set(&#39;Cache-Control&#39;, &#39;no-store&#39;);<br>  res.render(&#39;private-data&#39;, { data: fetchPrivateData() });<br>});</pre><p>This example uses HTTP headers to dictate that the response should not be stored in any cache, ensuring data privacy and integrity.</p><h4>4. Robust Security Headers</h4><p>HTTP headers play a crucial role in securing web applications. SSR provides better control over these headers, enhancing security against various types of attacks like clickjacking and XSS.</p><pre>// Setting HTTP headers in SSR<br>app.use((req, res, next) =&gt; {<br>  res.setHeader(&#39;X-Frame-Options&#39;, &#39;DENY&#39;);<br>  res.setHeader(&#39;Content-Security-Policy&#39;, &quot;default-src &#39;self&#39;&quot;);<br>  next();<br>});</pre><h4>Lack of Security Headers Client-Side:</h4><p>Client-side applications often only set security headers if specifically coded or configured.</p><h4>SSR Enhanced Header Management:</h4><p>On the server, you can globally apply security policies:</p><pre>// Global security headers in an SSR application<br>app.use((req, res, next) =&gt; {<br>  res.setHeader(&#39;X-Content-Type-Options&#39;, &#39;nosniff&#39;);<br>  res.setHeader(&#39;Referrer-Policy&#39;, &#39;no-referrer&#39;);<br>  next();<br>});</pre><p>These headers prevent MIME-type sniffing and control referrer information, enhancing overall security.</p><h3>Handling Network Requests in SSR vs. CSR</h3><p>When using server-side rendering (SSR), the behavior of network requests as seen in a browser’s network console can differ significantly from what you would observe in a client-side rendering (CSR) scenario. Here’s what happens in both cases:</p><h4>In Client-Side Rendering (CSR)</h4><ul><li><strong>Network Requests:</strong> When you load a CSR application, the initial HTML document usually contains minimal content — often just a skeleton or a loading spinner. After this initial load, JavaScript files and additional resources (like CSS, images, etc.) are fetched. These files include scripts that make further API calls to fetch data dynamically. These data requests and resource loads are visible in the browser’s network console.</li><li><strong>Visibility:</strong> All subsequent API calls made by JavaScript, along with requests for additional scripts, stylesheets, and other resources, are visible in the network console. This visibility is because the data-fetching and page-rendering logic is executed in the browser.</li></ul><h4>In Server-Side Rendering (SSR)</h4><ul><li><strong>Network Requests:</strong> In SSR, the server handles the rendering of the HTML page, which includes fetching all necessary data before sending a fully rendered HTML document to the client. This initial page load appears in the browser’s network console as a single request (for the HTML document), which already includes all the required data embedded within it.</li><li><strong>Visibility:</strong> The network console will not show the server-side API calls that the SSR framework makes to render the page. This is because those calls are made from the server to the APIs or databases, not from the user’s browser. Only requests that the client (browser) makes after the initial page load — such as fetching additional scripts, stylesheets, or making client-side API requests — will be visible.</li></ul><h4>Additional Considerations</h4><ul><li><strong>Client-Side API Requests:</strong> Even in SSR applications, any dynamic interactions that require updated data after the initial page load will still involve client-side API requests. These requests, like in a CSR scenario, will be visible in the network console. For instance, if a user interacts with a page element that triggers a data refresh or a new data load, those API calls will appear in the network console.</li><li><strong>Security Implication:</strong> One of the security advantages of SSR is that sensitive API requests, database queries, and other backend interactions that happen during the initial rendering on the server are not exposed to the client’s network console, providing a layer of obfuscation against potential attackers who inspect network activity to gather insights about backend processes.</li></ul><blockquote>Thank you for reading<br>Sincerely <a href="https://medium.com/u/d7911bb64fc8">Hajagha Hasanli</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b7208d8d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>