<?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 hamza alam on Medium]]></title>
        <description><![CDATA[Stories by hamza alam on Medium]]></description>
        <link>https://medium.com/@alamhamza873?source=rss-1f2a2d7d73b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MfT-BPzhSmjf1noKV7ct6Q.jpeg</url>
            <title>Stories by hamza alam on Medium</title>
            <link>https://medium.com/@alamhamza873?source=rss-1f2a2d7d73b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:05:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alamhamza873/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[PostgreSQL MVCC: How Tuple Visibility Works with xmin, xmax, pg_xact, and ProcArray]]></title>
            <link>https://medium.com/@alamhamza873/postgresql-mvcc-how-tuple-visibility-works-with-xmin-xmax-pg-xact-and-procarray-e752414750e7?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e752414750e7</guid>
            <category><![CDATA[postgresql-internal]]></category>
            <category><![CDATA[sql-database]]></category>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[mvcc]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 08:36:56 GMT</pubDate>
            <atom:updated>2026-09-02T08:36:56.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clients and the Client-Server Protocol</h3><p>Another task of the <strong>Postmaster</strong> is to listen for incoming client connections. When a client connects, the Postmaster starts a separate <strong>backend process</strong> for that connection. The client establishes a connection with the backend process and starts a session.</p><p>The session continues until the connection is closed, either because the client disconnects or because the connection is terminated.</p><p>The server starts a new backend process for each client connection. Having a large number of connections can therefore become a problem for PostgreSQL.</p><h3>Problems</h3><p><strong>• Memory usage:</strong> Each backend process requires its own memory for things such as catalog information, query execution state, and other data. As the number of connections increases, the overall memory consumption can increase significantly.</p><p><strong>• Process creation overhead:</strong> If a client connects, performs a very small query, and immediately disconnects, PostgreSQL still has to create and initialize a backend process for that connection. For very short-lived connections, this overhead can become significant.</p><p><strong>• Process management overhead:</strong> When many backend processes are running, the operating system has to manage and schedule more processes. As the number of processes increases, process management and context switching can add overhead and affect performance.</p><p>One way to address the large number of connections is <strong>connection pooling</strong>.</p><p>PostgreSQL does not provide a built-in general-purpose connection pooler, so external tools such as <strong>PgBouncer</strong> and <strong>Odyssey</strong> are commonly used.</p><p>In <strong>transaction pooling</strong> mode, a PostgreSQL backend process is not permanently assigned to a single client. Instead, when one client’s transaction finishes, the backend connection can be reused for another client’s transaction.</p><p>For example:</p><pre>Client A → Transaction → Backend 1<br>                         ↓<br>                    Transaction ends<br>                         ↓<br>Client B → Transaction → Backend 1</pre><p>This allows many client connections to share a smaller number of PostgreSQL backend connections, reducing resource usage and improving scalability.</p><p>However, transaction pooling imposes some restrictions on application design because applications cannot reliably depend on <strong>session-level state</strong>. A client may use a different PostgreSQL backend connection for its next transaction.</p><p>Therefore, session-level features such as temporary tables, session variables, prepared statements, and other session-specific state may not work as expected with transaction pooling unless the pooler and application are configured appropriately.</p><h3>Client-Server Protocol</h3><p>To communicate with PostgreSQL, both the client and server use the <strong>PostgreSQL frontend/backend protocol</strong>.</p><p>Client applications commonly communicate with PostgreSQL through <strong>libpq</strong>, which is PostgreSQL’s standard client library for C. Other programming languages and drivers can implement the PostgreSQL protocol themselves or use libraries that are built on top of libpq.</p><p>A connection is established to a particular <strong>database</strong> on behalf of a particular <strong>user/role</strong>.</p><p>A PostgreSQL server manages a <strong>database cluster</strong>, which can contain multiple databases. A client connection is connected to one database at a time. If an application needs to work with another database in the same cluster, it must establish a separate connection to that database.</p><p>After the connection is established, <strong>authentication</strong> takes place. The server verifies the client’s identity and determines whether the user/role is allowed to connect to the requested database.</p><p>Once the connection is authenticated, the client can send SQL commands to the backend process.</p><p>For a simple SQL query, the client sends the SQL statement as text. The backend process then:</p><ol><li><strong>Parses</strong> the SQL statement.</li><li><strong>Analyzes</strong> the statement and checks objects, permissions, and data types.</li><li><strong>Plans/optimizes</strong> the query by determining an execution plan.</li><li><strong>Executes</strong> the plan.</li><li><strong>Returns</strong> the result to the client using the PostgreSQL frontend/backend protocol.</li></ol><p>For example:</p><pre>Client<br>   │<br>   │  &quot;SELECT * FROM users;&quot;<br>   ▼<br>PostgreSQL Backend<br>   │<br>   ├── Parse<br>   ├── Analyze<br>   ├── Plan<br>   ├── Execute<br>   │<br>   ▼<br>Result<br>   │<br>   ▼<br>Client</pre><h3>ISOLATION</h3><h3>Consistency</h3><p>A key feature of a relational database is that it helps maintain <strong>data correctness and consistency</strong>.</p><p>At the database level, we can define constraints such as NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY. These constraints ensure that certain rules are never violated.</p><p>For example:</p><pre>CREATE TABLE users (<br>    id INT PRIMARY KEY,<br>    email VARCHAR(255) UNIQUE NOT NULL<br>);</pre><p>The database can guarantee that email cannot be NULL and that two users cannot have the same email.</p><p>However, some business rules are too complex to express using simple database constraints because they involve multiple rows or tables.</p><p>For example, suppose we have:</p><pre>Orders<br>-------<br>id<br>total_amount</pre><pre>Order_Items<br>-----------<br>id<br>order_id<br>price<br>quantity</pre><p>Suppose our business rule says:</p><pre>Orders.total_amount<br>=<br>SUM(Order_Items.price * Order_Items.quantity)</pre><p>If someone changes an item but does not update the order total, the database may still consider both rows valid because no standard constraint has necessarily been violated. However, from the application’s business perspective, the data is now inconsistent.</p><p>Such rules can be enforced using application logic, triggers, stored procedures, or more advanced database constraints.</p><p>Therefore, <strong>database integrity and business consistency are related but not exactly the same thing</strong>.</p><p>Database integrity refers to rules that the database can explicitly enforce. Business consistency can include additional rules that depend on the application’s domain.</p><p>If an important business rule is not represented in the database, the DBMS cannot automatically understand or enforce that rule. The application must therefore ensure that its operations preserve the required business rules.</p><h3>Consistency During a Transaction</h3><p>There is another important point: a correct transaction can temporarily move the database through an intermediate state that would not satisfy the final business rule.</p><p>For example, suppose:</p><pre>Account A = $100<br>Account B = $200</pre><pre>Total = $300</pre><p>We want to transfer $100 from A to B.</p><p>The transaction performs two operations:</p><pre>BEGIN;</pre><pre>UPDATE accounts<br>SET balance = balance - 100<br>WHERE id = &#39;A&#39;;</pre><pre>UPDATE accounts<br>SET balance = balance + 100<br>WHERE id = &#39;B&#39;;</pre><pre>COMMIT;</pre><p>After the first operation:</p><pre>Account A = $0<br>Account B = $200</pre><pre>Total = $200</pre><p>The intermediate state does not satisfy our expected total of $300.</p><p>After the second operation:</p><pre>Account A = $0<br>Account B = $300</pre><pre>Total = $300</pre><p>The database is back in a valid state.</p><p>This is perfectly normal. A transaction may temporarily pass through intermediate states that are not valid from the application’s business perspective. What matters is that the transaction <strong>ends in a valid state if it commits</strong>.</p><p>If the server crashes after the first operation but before the second operation, the transaction must not leave the database in that intermediate state.</p><p>This is where <strong>atomicity</strong> becomes important.</p><p>The two operations are treated as one transaction:</p><pre>BEGIN<br>          │<br>          ▼<br>   Subtract $100 from A<br>          │<br>          ▼<br>    Add $100 to B<br>          │<br>          ▼<br>       COMMIT</pre><p>If the transaction fails before COMMIT, PostgreSQL can roll back its changes:</p><pre>UPDATE A<br>      ↓<br>UPDATE B  ← failure<br>      ↓<br>ROLLBACK<br>      ↓<br>Original state restored</pre><p>Therefore, atomicity ensures that a transaction’s changes are treated as an <strong>all-or-nothing unit</strong>.</p><h3>Why Do We Need Isolation?</h3><p>Now we reach the main topic: <strong>Isolation</strong>.</p><p>Suppose two transactions execute at the same time.</p><pre>Transaction A                 Transaction B</pre><pre>Read balance = $100<br>                              Read balance = $100</pre><pre>Subtract $50<br>                              Subtract $50</pre><pre>Write $50<br>                              Write $50</pre><p>Both transactions may have read the same original value.</p><p>If they are not properly coordinated, one transaction’s result can overwrite the other’s result.</p><p>The problem is that transactions are executing <strong>concurrently</strong>.</p><p>One obvious solution would be:</p><pre>Transaction A<br>     ↓<br>Finish completely<br>     ↓<br>Transaction B<br>     ↓<br>Finish completely<br>     ↓<br>Transaction C</pre><p>In other words, execute transactions strictly one after another.</p><p>This would make reasoning about correctness much easier.</p><p>However, it would severely reduce <strong>concurrency and performance</strong>.</p><p>Imagine a database has 1,000 transactions.</p><p>If every transaction had to completely finish before the next one could begin, a transaction that is waiting for disk I/O, network I/O, or some other resource would block every transaction behind it.</p><p>Instead, databases allow transactions to execute concurrently and use <strong>concurrency-control mechanisms</strong> to prevent or manage incorrect interactions between them.</p><p>This is the purpose of <strong>isolation</strong>.</p><h3>What Does Isolation Mean?</h3><p>Isolation means that concurrently executing transactions should not interfere with each other in a way that produces unacceptable results.</p><p>The important point is that isolation does <strong>not necessarily mean that transactions literally execute one at a time</strong>.</p><p>Instead, the database controls their interactions so that the result behaves according to the guarantees provided by the selected <strong>isolation level</strong>.</p><p>For example, PostgreSQL provides isolation levels such as:</p><pre>Read Committed<br>Repeatable Read<br>Serializable</pre><p>Each level provides different guarantees and allows different amounts of concurrency.</p><p>Higher isolation generally provides stronger protection against concurrency anomalies, but it can also reduce concurrency or increase the possibility of transaction retries/serialization failures.</p><h3>Transactions and ACID</h3><p>A transaction is a group of database operations that should take the database from one valid state to another valid state.</p><p>The <strong>ACID</strong> properties describe important guarantees provided by the database system:</p><pre>A → Atomicity<br>C → Consistency<br>I → Isolation<br>D → Durability</pre><p>These properties are closely related and work together, but they describe different guarantees.</p><h3>Atomicity</h3><p>A transaction is treated as an all-or-nothing unit.</p><pre>All operations succeed<br>        OR<br>All operations are rolled back</pre><h3>Consistency</h3><p>A successfully committed transaction should preserve the database’s defined integrity constraints and, when correctly implemented, the application’s required business invariants.</p><h3>Isolation</h3><p>Concurrent transactions should not interfere with each other in ways that violate the guarantees of the selected isolation level.</p><h3>Durability</h3><p>Once a transaction has been committed, its changes must survive failures such as a server crash or power failure.</p><h3>Durability and Crash Recovery</h3><p>Durability is closely connected to crash recovery.</p><p>Suppose:</p><pre>Transaction A<br>     │<br>     ├── UPDATE<br>     ├── UPDATE<br>     └── COMMIT</pre><p>Once PostgreSQL reports that the transaction has committed, its changes must not simply disappear because the server crashes.</p><p>PostgreSQL uses mechanisms such as <strong>Write-Ahead Logging (WAL)</strong> to make committed changes recoverable after a crash.</p><p>During recovery, PostgreSQL reconstructs the database state using the WAL.</p><p>The simplified idea is:</p><pre>Committed changes<br>      ↓<br>Must survive crash</pre><pre>Uncommitted transaction<br>      ↓<br>Must not remain partially applied</pre><p>This is why atomicity and durability are closely related to crash recovery.</p><h3>Database vs Application Responsibilities</h3><p>The DBMS and the application share responsibility for maintaining correct data.</p><h3>The DBMS is responsible for things such as:</h3><ul><li>Atomicity</li><li>Concurrency control and isolation</li><li>Durability</li><li>Enforcing declared constraints</li><li>Maintaining the internal consistency of database operations</li><li>Crash recovery</li></ul><h3>The Application is responsible for things such as:</h3><ul><li>Business rules</li><li>Domain-specific invariants</li><li>Correct transaction boundaries</li><li>Validating business operations</li><li>Using appropriate database constraints where possible</li></ul><p>For example, suppose a banking application has the rule:</p><pre>Account balance must never be negative.</pre><p>If this rule has not been represented in a database constraint or other database mechanism, the DBMS does not automatically know that this is a business requirement.</p><p>The application must ensure that its transactions do not violate this rule.</p><p>However, this does <strong>not</strong> mean that the application should ignore the database’s capabilities. Whenever a business rule can safely be enforced by the database, it is often beneficial to enforce it there as well.</p><h3>Why Isolation Levels Matter</h3><p>Full isolation is not always necessary.</p><p>The strongest standard isolation level is <strong>Serializable</strong>. It provides the strongest protection against anomalies caused by concurrent transactions, but achieving this can reduce concurrency and may cause transactions to fail and require retrying.</p><p>Therefore, databases provide different isolation levels that allow developers to choose an appropriate balance between:</p><pre>Correctness<br>     ↕<br>Concurrency<br>     ↕<br>Performance</pre><p>For example:</p><pre>Read Committed<br>      ↓<br>More concurrency<br>Weaker guarantees</pre><pre>Repeatable Read<br>      ↓<br>Stronger guarantees</pre><pre>Serializable<br>      ↓<br>Strongest isolation<br>Potentially lower concurrency</pre><p>Therefore, developers need to understand the different isolation levels and the anomalies they can allow or prevent.</p><p>The goal is not simply to choose the strongest isolation level. The goal is to choose the <strong>appropriate isolation level for the application’s requirements</strong>.</p><h3>Isolation Levels and Anomalies Defined by the SQL Standard</h3><p>The SQL standard defines <strong>four isolation levels</strong>:</p><ol><li>Read Uncommitted</li><li>Read Committed</li><li>Repeatable Read</li><li>Serializable</li></ol><p>These isolation levels are defined in terms of which kinds of <strong>concurrency phenomena (anomalies)</strong> may be observed when transactions execute concurrently.</p><p>Therefore, when learning about isolation, it is useful to first understand the anomalies that can occur during concurrent transaction execution.</p><h3>Anomalies</h3><h3>1. Lost Update</h3><p>A <strong>lost update</strong> occurs when two transactions read the same data, calculate new values based on that data, and then one transaction overwrites the update made by the other transaction.</p><h3>Example</h3><p>Suppose an account balance is:</p><pre>$100</pre><p>Transaction A reads:</p><pre>$100</pre><p>Transaction B also reads:</p><pre>$100</pre><p>Transaction A adds $1 and writes:</p><pre>$101</pre><p>Transaction B, unaware of Transaction A’s update, also calculates:</p><pre>$100 + $1 = $101</pre><p>and writes:</p><pre>$101</pre><p>The final balance is:</p><pre>$101</pre><p>but it should be:</p><pre>$102</pre><p>Transaction A’s update has therefore been overwritten.</p><p>This is called a <strong>lost update</strong>.</p><blockquote><em>Note: Lost update is a commonly discussed concurrency anomaly, but the SQL standard’s classic isolation-level definitions are primarily expressed in terms of dirty reads, non-repeatable reads, and phantom reads.</em></blockquote><h3>2. Dirty Read</h3><p>A <strong>dirty read</strong> occurs when one transaction reads changes made by another transaction <strong>before those changes have been committed</strong>.</p><h3>Example</h3><p>Initially:</p><pre>Account balance = $0</pre><p>Transaction A starts:</p><pre>BEGIN;</pre><pre>UPDATE accounts<br>SET balance = 100;</pre><p>Transaction A has not committed yet.</p><p>Transaction B reads the account and sees:</p><pre>$100</pre><p>Transaction B has therefore read an <strong>uncommitted value</strong>.</p><p>Now suppose Transaction A encounters an error:</p><pre>ROLLBACK;</pre><p>The database returns to:</p><pre>$0</pre><p>The $100 that Transaction B previously observed never actually became part of the committed database state.</p><p>That is a <strong>dirty read</strong>.</p><p>The SQL standard permits dirty reads at the <strong>Read Uncommitted</strong> isolation level.</p><p>However, PostgreSQL does <strong>not actually allow dirty reads</strong>. In PostgreSQL, Read Uncommitted behaves like Read Committed.</p><h3>3. Non-Repeatable Read</h3><p>A <strong>non-repeatable read</strong> occurs when the same transaction reads the same row twice, but another transaction modifies and commits that row between the two reads.</p><h3>Example</h3><p>Suppose:</p><pre>Account balance = $100</pre><p>Transaction T1 reads:</p><pre>$100</pre><p>T2 then updates the account:</p><pre>$100 → $0</pre><p>and commits.</p><p>T1 reads the same row again and gets:</p><pre>$0</pre><p>The same transaction has now observed two different values for the same row.</p><p>This is a <strong>non-repeatable read</strong>.</p><p>The important sequence is:</p><pre>T1: READ → $100</pre><pre>T2: UPDATE → $0<br>T2: COMMIT</pre><pre>T1: READ → $0</pre><p>Under PostgreSQL’s <strong>Read Committed</strong> isolation level, this behavior is possible because each statement normally obtains its own snapshot.</p><p>Under <strong>Repeatable Read</strong>, T1 continues to see a consistent snapshot, so it does not see the later committed version in the same way.</p><h3>4. Phantom Read</h3><p>A <strong>phantom read</strong> occurs when the same transaction executes the same query twice, but the second execution returns a <strong>different set of rows</strong> because another transaction inserted or deleted rows that satisfy the query condition and committed those changes.</p><p>The key difference is:</p><pre>Non-repeatable read<br>→ Existing row changes.</pre><pre>Phantom read<br>→ Set of matching rows changes.</pre><h3>Example</h3><p>Suppose there is a business rule:</p><pre>A client can own at most 3 bank accounts.</pre><p>Transaction T1 checks the client’s accounts:</p><pre>SELECT *<br>FROM accounts<br>WHERE client_id = 1;</pre><p>The query returns:</p><pre>Account A<br>Account B</pre><p>T1 therefore sees:</p><pre>2 accounts</pre><p>and decides that creating another account is allowed.</p><p>Before T1 finishes, T2 creates another account:</p><pre>Account C</pre><p>and commits.</p><p>If T1 executes the same query again, it may now see:</p><pre>Account A<br>Account B<br>Account C</pre><p>The result set has changed because a new row now satisfies the query condition.</p><p>That newly appearing row is called a <strong>phantom row</strong>.</p><h3>Important distinction</h3><pre>Non-repeatable read:</pre><pre>First:<br>A = $100</pre><pre>Second:<br>A = $50</pre><pre>Same row, different value.</pre><p>versus:</p><pre>Phantom read:</pre><pre>First:<br>A<br>B</pre><pre>Second:<br>A<br>B<br>C</pre><pre>Different set of rows.</pre><p>The SQL standard’s definition of Repeatable Read does not require every database implementation to prevent phantoms in exactly the same way.</p><p>PostgreSQL’s <strong>Repeatable Read does prevent phantom reads</strong> because of its snapshot-based implementation.</p><h3>No Anomalies and Serializable</h3><p><strong>Serializable</strong> is the strongest isolation level defined by the SQL standard.</p><p>The goal of Serializable isolation is stronger than simply preventing the commonly discussed anomalies.</p><p>The database guarantees that the result of concurrently executing transactions is equivalent to the result of <strong>some serial execution</strong> of those transactions.</p><p>For example, suppose we have:</p><pre>T1<br>T2<br>T3</pre><p>A serial execution could be:</p><pre>T1 → T2 → T3</pre><p>or:</p><pre>T2 → T3 → T1</pre><p>or another valid ordering.</p><p>The database may actually execute the transactions concurrently:</p><pre>T1 ──────────────<br>       T2 ─────────────<br>            T3 ───────────</pre><p>but the final result must be equivalent to some serial ordering.</p><p>This is why the name <strong>Serializable</strong> is used.</p><p>It also protects against concurrency problems that are not captured by the three classic read anomalies, such as <strong>write skew</strong>.</p><p>Therefore, under Serializable isolation, developers can reason about each transaction approximately as if it were running alone, while the database handles the concurrency control.</p><p>However, Serializable transactions may be <strong>aborted/rejected because of serialization conflicts</strong>, and the application may need to retry them.</p><h3>Isolation Levels in PostgreSQL</h3><p>One of the major techniques used by modern databases to support concurrent transactions is <strong>Multi-Version Concurrency Control (MVCC)</strong>.</p><p>PostgreSQL uses MVCC.</p><p>Instead of modifying an existing row version directly, PostgreSQL generally creates a <strong>new row version</strong> when a row is updated.</p><p>Conceptually:</p><pre>Old row version<br>      ↓<br>New row version<br>      ↓<br>Another new row version</pre><p>Different transactions can therefore see different versions depending on their snapshots.</p><p>For example:</p><pre>T1<br> │<br> └── sees old version</pre><pre>T2<br> │<br> └── creates new version</pre><p>T1 can continue seeing the version that is visible to its snapshot while T2 works with the newer version.</p><p>This allows PostgreSQL to provide high concurrency without requiring every reader to wait for every writer.</p><h3>Snapshot and MVCC</h3><p>It is important to distinguish <strong>MVCC</strong> from <strong>snapshot-based isolation</strong>.</p><h3>MVCC</h3><p>MVCC is a mechanism for maintaining multiple versions of rows.</p><h3>Snapshot</h3><p>A snapshot is information that PostgreSQL uses to determine which transaction changes are visible to a particular statement or transaction.</p><p>The exact snapshot behavior depends on the isolation level.</p><p>For PostgreSQL’s <strong>Read Committed</strong>:</p><pre>Transaction T1</pre><pre>Statement 1<br>    ↓<br>Snapshot 1</pre><pre>Statement 2<br>    ↓<br>Snapshot 2</pre><p>Each statement normally obtains a new snapshot.</p><p>Therefore, another transaction can commit a change between T1’s two statements, and T1’s second statement may see that newly committed change.</p><p>For PostgreSQL’s <strong>Repeatable Read</strong>:</p><pre>Transaction T1</pre><pre>Snapshot<br>   │<br>   ├── Statement 1<br>   ├── Statement 2<br>   ├── Statement 3<br>   └── ...</pre><p>The transaction uses a consistent snapshot, so later statements do not see changes committed after that snapshot.</p><h3>Which Isolation Level Should We Use?</h3><p>PostgreSQL’s default isolation level is:</p><pre>Read Committed</pre><p>It is widely used because it provides a useful balance between:</p><pre>Correctness<br>Concurrency<br>Performance</pre><p>However, Read Committed allows certain concurrency phenomena, such as non-repeatable reads.</p><p>Therefore, developers must design their transactions carefully.</p><p>If an application requires stronger guarantees, it can use:</p><pre>Repeatable Read</pre><p>or:</p><pre>Serializable</pre><p>The goal is not simply to use the strongest isolation level everywhere.</p><p>Instead, the application should choose an isolation level that provides the required correctness guarantees while allowing sufficient concurrency.</p><h3>Pages and Tuples</h3><p>Now we can connect <strong>MVCC</strong> to PostgreSQL’s physical storage.</p><p>PostgreSQL stores table and index data in fixed-size blocks called <strong>pages</strong>.</p><p>The default page size is normally:</p><pre>8 KB</pre><p>A page contains several important areas.</p><h3>Page Structure</h3><p>A PostgreSQL page can conceptually be divided into five areas:</p><pre>┌──────────────────────────────┐<br>│ Page Header                  │<br>├──────────────────────────────┤<br>│ Item Pointer Array           │<br>├──────────────────────────────┤<br>│                              │<br>│ Free Space                   │<br>│                              │<br>├──────────────────────────────┤<br>│ Tuple / Row Versions         │<br>│                              │<br>├──────────────────────────────┤<br>│ Special Space                │<br>└──────────────────────────────┘</pre><p>These are:</p><ol><li><strong>Page Header</strong></li><li><strong>Item Pointer Array</strong></li><li><strong>Free Space</strong></li><li><strong>Tuple / Row Versions</strong></li><li><strong>Special Space</strong></li></ol><p>The special space is primarily used by indexes. Heap/table pages generally do not use it in the same way.</p><h3>Page Header</h3><p>The <strong>page header</strong> is located at the beginning of the page.</p><p>It contains metadata about the page, including information such as:</p><ul><li>Page LSN</li><li>Checksum</li><li>Free-space boundaries</li><li>Page layout information</li><li>Other page metadata</li></ul><p>A checksum can be used to detect corruption or unexpected modification of a page.</p><h3>Special Space</h3><p>The <strong>special space</strong> is located at the end of the page.</p><p>It is primarily used by index pages.</p><p>For example, B-tree index pages contain additional metadata required by the B-tree implementation. This includes links between sibling pages.</p><p>Conceptually:</p><pre>Previous sibling<br>       ↑<br>       │<br>   [B-tree Page]<br>       │<br>       ↓<br>Next sibling</pre><p>This allows B-tree operations to navigate between sibling pages efficiently.</p><h3>Item Pointers</h3><p>The <strong>item pointer array</strong> acts like a directory inside the page.</p><p>Each item pointer identifies the location of a tuple within the page.</p><p>Conceptually:</p><pre>Item Pointer Array</pre><pre>Slot 1 ─────→ Tuple A<br>Slot 2 ─────→ Tuple B<br>Slot 3 ─────→ Tuple C</pre><p>This provides an additional level of indirection between a tuple’s identifier and its actual physical location.</p><p>PostgreSQL uses a <strong>TID (Tuple Identifier)</strong> to identify a physical tuple location.</p><p>Conceptually, a TID contains:</p><pre>(Block Number, Offset Number)</pre><p>The block number identifies the page, while the offset number identifies the tuple’s <strong>item pointer/slot</strong> within that page.</p><p>Therefore:</p><pre>TID<br> │<br> ├── Block Number<br> │       ↓<br> │     Page<br> │<br> └── Offset Number<br>         ↓<br>   Item Pointer<br>         ↓<br>      Tuple</pre><p>This indirection is useful because the physical location of a tuple within a page can change without requiring indexes to store the tuple’s byte offset directly.</p><h3>Why Use Item Pointers?</h3><p>Imagine an index directly stored the byte address of a tuple:</p><pre>Index<br>  │<br>  └──→ byte offset 400</pre><p>If the tuple moved to offset 500, the index would need to be updated.</p><p>PostgreSQL instead uses an item pointer:</p><pre>Index<br>  │<br>  └──→ TID<br>          │<br>          ↓<br>     Item Pointer<br>          │<br>          ↓<br>       Tuple</pre><p>If the tuple’s location within the page changes, PostgreSQL can update the item pointer rather than changing every index reference.</p><p>This is the purpose of the <strong>indirection</strong>.</p><h3>Tuples</h3><p>A PostgreSQL table row is more precisely called a <strong>tuple</strong>.</p><p>A tuple contains:</p><ul><li>Tuple header</li><li>User data</li><li>MVCC-related metadata</li><li>Other internal information</li></ul><p>PostgreSQL uses MVCC, so an update generally does not simply overwrite the old tuple version.</p><p>Instead:</p><pre>Old tuple version<br>       │<br>       │ UPDATE<br>       ↓<br>New tuple version</pre><p>Multiple versions of the same logical row can therefore exist in the table at the same time.</p><p>For example:</p><pre>Tuple Version 1<br>xmin = 100<br>xmax = 105</pre><pre>Tuple Version 2<br>xmin = 105<br>xmax = ...</pre><p>PostgreSQL uses this information to determine which version is visible to a particular transaction.</p><h3>Free Space</h3><p>Free space exists between the <strong>item pointer array</strong> and the <strong>tuple data</strong>.</p><p>Conceptually:</p><pre>Page beginning<br>     ↓<br>[Header]<br>[Item Pointers]<br>     ↓<br>   FREE SPACE<br>     ↑<br>[Tuples]<br>     ↑<br>Page end</pre><p>The item pointer array grows from the beginning of the page toward the end.</p><p>Tuple storage grows from the end of the page toward the beginning.</p><p>Therefore, the free space between them can be used for new tuples or additional item pointers.</p><p>This design allows the page to keep its free space largely consolidated rather than scattering it throughout the page.</p><h3>Row Version Layout</h3><p>Each tuple consists of a <strong>tuple header followed by the tuple’s data</strong>.</p><p>The tuple header contains several pieces of metadata.</p><p>Important fields include:</p><ul><li>xmin</li><li>xmax</li><li>t_infomask</li><li>t_infomask2</li><li>t_ctid</li></ul><p>Among these, xmin and xmax are especially important for understanding MVCC.</p><h3>xmin and xmax</h3><p>Each tuple version contains transaction-related information.</p><h3>xmin</h3><p>xmin identifies the transaction that inserted the tuple version.</p><h3>xmax</h3><p>xmax normally identifies the transaction that deleted the tuple version or made it obsolete through an update.</p><p>However, xmin and xmax do <strong>not simply represent a start time and end time</strong>.</p><p>They are transaction IDs.</p><p>PostgreSQL combines:</p><pre>xmin<br>xmax<br>transaction status<br>current transaction&#39;s snapshot</pre><p>to determine whether a particular tuple version is visible.</p><p>Conceptually:</p><pre>Tuple<br> │<br> ├── xmin<br> ├── xmax<br> └── other metadata<br>        │<br>        ↓<br>Current transaction&#39;s snapshot<br>        │<br>        ↓<br>Is this tuple version visible?</pre><h3>Infomask</h3><p>t_infomask is a <strong>bit field</strong> stored in the tuple header.</p><p>Individual bits represent different pieces of information about the tuple.</p><p>PostgreSQL uses these bits to efficiently determine properties and conditions associated with the tuple.</p><p>There is also another related field called:</p><pre>t_infomask2</pre><p>Both fields contain internal tuple metadata.</p><h3>CTID</h3><p>ctid is a physical identifier for a tuple version.</p><p>It is represented conceptually as:</p><pre>(block number, item pointer/offset number)</pre><p>For example:</p><pre>(10, 5)</pre><p>means:</p><pre>Page/Block 10<br>Item Pointer 5</pre><p>ctid is therefore not a C/C++ memory pointer.</p><p>It identifies the physical location of a tuple version inside the table.</p><p>An important consequence is that <strong>ctid can change when a row is updated</strong>, because the update creates a new tuple version.</p><p>Therefore, ctid should not normally be treated as a permanent logical identifier for a row.</p><h3>Null Bitmap</h3><p>A tuple can contain a <strong>NULL bitmap</strong>.</p><p>The bitmap contains bits corresponding to nullable columns.</p><p>Conceptually:</p><pre>Column:   A    B    C    D<br>          │    │    │    │<br>Bitmap:   0    1    0    1</pre><p>The bitmap tells PostgreSQL which attributes are NULL.</p><p>The tuple header also contains important MVCC metadata such as:</p><pre>xmin<br>xmax</pre><p>Because every tuple carries a header containing metadata, the overhead can be significant for very small rows.</p><h3>Operations on Tuples</h3><p>PostgreSQL uses xmin and xmax as part of its MVCC mechanism.</p><p>These values are <strong>transaction IDs</strong>, not actual timestamps.</p><p>Suppose transaction 100 creates a row:</p><pre>xmin = 100<br>xmax = 0</pre><p>Conceptually:</p><pre>Transaction 100<br>      │<br>      ↓<br>creates tuple</pre><pre>xmin = 100</pre><p>If transaction 105 later updates that row, PostgreSQL creates a new tuple version.</p><p>The old version becomes obsolete:</p><pre>Old version:<br>xmin = 100<br>xmax = 105</pre><pre>New version:<br>xmin = 105<br>xmax = 0</pre><p>Conceptually:</p><pre>Old Tuple<br>xmin=100<br>xmax=105<br>     │<br>     │ UPDATE by T105<br>     ↓<br>New Tuple<br>xmin=105<br>xmax=0</pre><p>The exact physical and visibility behavior is more complex than this simplified model, but this is a useful way to understand the basic MVCC relationship between tuple versions.</p><h3>DELETE</h3><p>When a transaction deletes a row, PostgreSQL records the deleting transaction’s ID in the tuple’s xmax.</p><p>For example:</p><pre>Before DELETE:</pre><pre>xmin = 100<br>xmax = 0</pre><p>Transaction 105 deletes the row:</p><pre>xmin = 100<br>xmax = 105</pre><p>This does not immediately mean that the tuple’s storage is physically removed.</p><p>Transaction 105 could still abort.</p><p>If transaction 105 commits, the old tuple version becomes invisible to transactions for which the deletion is visible.</p><p>If transaction 105 aborts, the deletion does not take effect from the perspective of normal visibility.</p><p>The old tuple version can therefore remain physically present until PostgreSQL’s cleanup mechanisms, particularly <strong>VACUUM</strong>, determine that it is no longer needed.</p><h3>UPDATE</h3><p>An UPDATE can be understood at a simplified level as creating a new tuple version.</p><p>Suppose we start with:</p><pre>Old tuple:</pre><pre>xmin = 100<br>xmax = 0</pre><p>Transaction 105 updates it.</p><p>Conceptually:</p><pre>Old tuple:</pre><pre>xmin = 100<br>xmax = 105<br></pre><pre>New tuple:</pre><pre>xmin = 105<br>xmax = 0</pre><p>Therefore:</p><pre>Old version<br>     │<br>     │ UPDATE<br>     ↓<br>New version</pre><p>This is one of the fundamental mechanisms behind PostgreSQL’s MVCC implementation.</p><h3>Transaction Status</h3><p>Once a transaction finishes, PostgreSQL needs to know whether that transaction:</p><pre>COMMITTED</pre><p>or:</p><pre>ABORTED</pre><p>This information is important because tuple visibility depends partly on the status of the transactions represented by xmin and xmax.</p><p>PostgreSQL stores transaction status information in the:</p><pre>pg_xact</pre><p>directory.</p><p>In older PostgreSQL versions, this was called:</p><pre>pg_clog</pre><p>The name was later changed to pg_xact.</p><p>Conceptually:</p><pre>Transaction ID<br>      │<br>      ↓<br>   pg_xact<br>      │<br>      ↓<br>COMMITTED / ABORTED</pre><p>An active transaction has not yet completed, so its final committed/aborted status is not yet recorded as a completed transaction.</p><h3>How pg_xact Helps MVCC</h3><p>Suppose a tuple contains:</p><pre>xmin = 500</pre><p>This tells PostgreSQL:</p><blockquote><em>Transaction 500 created this tuple.</em></blockquote><p>Now PostgreSQL needs to determine whether transaction 500 committed.</p><p>It can consult transaction-status information in pg_xact.</p><p>Conceptually:</p><pre>Tuple<br>xmin = 500<br>   │<br>   ↓<br>Check transaction 500<br>   │<br>   ↓<br>pg_xact<br>   │<br>   ├── COMMITTED<br>   └── ABORTED</pre><p>But transaction status alone is not enough.</p><p>PostgreSQL also needs the current transaction’s <strong>MVCC snapshot</strong> to determine whether the tuple version is visible to the current transaction.</p><p>Therefore:</p><pre>Tuple metadata<br>      +<br>Transaction status<br>      +<br>Current snapshot<br>      ↓<br>Visibility decision</pre><p>This is the core idea behind PostgreSQL’s MVCC visibility mechanism.</p><h3>ProcArray</h3><p>PostgreSQL also maintains a shared-memory structure called the <strong>ProcArray</strong>.</p><p>It contains information about active backend processes and their transaction-related state.</p><p>PostgreSQL uses this information when constructing and evaluating snapshots and determining which transactions are currently active.</p><p>Conceptually:</p><pre>Backend 1 → Transaction 501<br>Backend 2 → Transaction 502<br>Backend 3 → Transaction 503</pre><pre>              ↓</pre><pre>          ProcArray</pre><p>Suppose transaction 502 is still active.</p><p>A snapshot can therefore know that transaction 502 has not yet committed or aborted.</p><p>This information is important when PostgreSQL determines whether tuple versions created or modified by concurrent transactions should be visible.</p><p>Therefore, MVCC visibility can be thought of as involving several pieces working together:</p><pre>Tuple<br>        ┌─────────────┐<br>        │ xmin / xmax │<br>        │ infomask    │<br>        │ ctid        │<br>        └──────┬──────┘<br>               │<br>               ↓<br>      Transaction Status<br>            pg_xact<br>               │<br>               +<br>               │<br>               ↓<br>          MVCC Snapshot<br>               │<br>               +<br>               │<br>               ↓<br>        ProcArray / active<br>          transaction info<br>               │<br>               ↓<br>       Visibility Decision</pre><p>This is why PostgreSQL’s MVCC system is more than simply storing xmin and xmax: those fields are inputs into a larger visibility mechanism.</p><h3>Commits and Transaction Status</h3><p>Once a transaction finishes, PostgreSQL needs to know whether the transaction <strong>committed or aborted</strong>. This information is important because PostgreSQL uses transaction status when determining whether a tuple version is visible to a particular transaction.</p><p>For this purpose, PostgreSQL uses the pg_xact directory. It contains internal files that store the <strong>commit/abort status of transactions</strong>.</p><p>In older PostgreSQL versions, this information was associated with the directory called pg_clog (Commit Log). It was later renamed to pg_xact because pg_clog could give the misleading impression that it was a traditional database log.</p><p>Conceptually:</p><pre>Transaction ID<br>      │<br>      ↓<br>   pg_xact<br>      │<br>      ├── COMMITTED<br>      │<br>      └── ABORTED</pre><p>This information is important for <strong>MVCC</strong> because tuple versions contain transaction IDs such as xmin and xmax.</p><h3>How pg_xact Is Used</h3><p>Suppose PostgreSQL encounters a tuple with:</p><pre>xmin = 500</pre><p>xmin tells PostgreSQL:</p><blockquote><em>Transaction 500 created this tuple version.</em></blockquote><p>PostgreSQL then needs to know what happened to transaction 500.</p><p>It can consult the transaction-status information in pg_xact:</p><pre>Tuple<br>xmin = 500<br>   │<br>   ↓<br>Check transaction 500<br>   │<br>   ↓<br>  pg_xact<br>   │<br>   ├── COMMITTED<br>   └── ABORTED</pre><p>However, knowing whether transaction 500 committed or aborted is <strong>not by itself enough</strong> to determine whether the tuple is visible.</p><p>PostgreSQL also needs the current transaction’s <strong>MVCC snapshot</strong>.</p><p>Therefore, visibility is conceptually determined using:</p><pre>Tuple metadata<br>     +<br>Transaction status<br>     +<br>Current MVCC snapshot<br>     ↓<br>Is this tuple version visible?</pre><h3>What Happens When a Transaction Commits?</h3><p>Suppose transaction 500 inserts a row:</p><pre>Transaction 500<br>      │<br>      ↓<br>Creates tuple</pre><pre>xmin = 500</pre><p>Initially, transaction 500 is still running.</p><p>After:</p><pre>COMMIT;</pre><p>PostgreSQL records transaction 500 as <strong>committed</strong> in pg_xact.</p><p>Conceptually:</p><pre>Before COMMIT:</pre><pre>Transaction 500<br>     ↓<br>ACTIVE<br></pre><pre>After COMMIT:</pre><pre>Transaction 500<br>     ↓<br>COMMITTED<br>     ↓<br>pg_xact</pre><p>Other transactions can then determine, according to their snapshots, whether the tuple created by transaction 500 is visible to them.</p><h3>What Happens When a Transaction Aborts?</h3><p>Suppose transaction 500 creates a tuple but later executes:</p><pre>ROLLBACK;</pre><p>PostgreSQL records transaction 500 as <strong>aborted</strong>.</p><p>Conceptually:</p><pre>Transaction 500<br>     ↓<br>ABORTED<br>     ↓<br>pg_xact</pre><p>The tuple physically created by the transaction does not necessarily disappear immediately.</p><p>Instead, its transaction status tells PostgreSQL that the tuple was created by an aborted transaction, so normal MVCC visibility rules will not treat that tuple as a valid committed row version.</p><p>Later, <strong>VACUUM</strong> can clean up tuple versions that are no longer needed.</p><h3>Active Transactions and ProcArray</h3><p>There is another important structure called <strong>ProcArray</strong>.</p><p>ProcArray is a shared-memory structure associated with PostgreSQL’s active backend processes and their transaction state.</p><p>It is important when PostgreSQL creates and evaluates MVCC snapshots because PostgreSQL needs to know which transactions are currently active.</p><p>Conceptually:</p><pre>Backend 1 → Transaction 501<br>Backend 2 → Transaction 502<br>Backend 3 → Transaction 503</pre><pre>              ↓</pre><pre>          ProcArray</pre><p>Suppose transaction 502 is currently running.</p><p>When PostgreSQL considers a snapshot, it needs to know that transaction 502 is still active and therefore has not yet reached a final committed or aborted state.</p><p>This information is different from the persistent transaction status stored in pg_xact.</p><p>We can therefore think of the two structures at a high level as:</p><pre>pg_xact<br>   ↓<br>Persistent transaction status<br>   ↓<br>COMMITTED / ABORTED<br></pre><pre>ProcArray<br>   ↓<br>Currently active transaction information<br>   ↓<br>Which transactions are still running?</pre><p>Together with the tuple’s xmin/xmax and the current snapshot, PostgreSQL can determine tuple visibility.</p><h3>Putting Everything Together</h3><p>Suppose we have:</p><pre>Tuple:</pre><pre>xmin = 500<br>xmax = 0</pre><p>This means transaction 500 created the tuple, and there is currently no deleting/updating transaction recorded in xmax.</p><p>PostgreSQL wants to know whether the tuple is visible to transaction 600.</p><p>It conceptually performs something like:</p><pre>Tuple<br>             xmin = 500<br>                  │<br>                  ▼<br>          Is transaction 500<br>             committed?<br>                  │<br>            ┌─────┴─────┐<br>            │           │<br>           Yes          No<br>            │           │<br>            ▼           ▼<br>       Check snapshot   Not visible<br>            │<br>            ▼<br>     Is 500 visible to<br>     transaction 600?<br>            │<br>            ▼<br>     Visibility decision</pre><p>The actual PostgreSQL implementation is more sophisticated and optimized than this simplified diagram, but this is the correct mental model.</p><p>The important thing to remember is:</p><blockquote><strong><em>xmin tells us which transaction created the tuple, </em></strong><strong><em>pg_xact helps us determine the transaction&#39;s final status, ProcArray helps PostgreSQL track active transactions, and the MVCC snapshot determines whether that tuple version is visible to the current transaction.</em></strong></blockquote><h3>Why This Matters for MVCC</h3><p>This mechanism allows PostgreSQL to keep multiple versions of a logical row.</p><p>For example:</p><pre>Logical Row<br>     │<br>     ├── Version 1<br>     │     xmin = 100<br>     │     xmax = 200<br>     │<br>     └── Version 2<br>           xmin = 200<br>           xmax = 0</pre><p>PostgreSQL can determine which version a transaction should see by examining:</p><pre>Tuple metadata<br>      +<br>Transaction status<br>      +<br>MVCC snapshot</pre><p>This is the foundation of PostgreSQL’s <strong>Multi-Version Concurrency Control</strong>.</p><p>Old tuple versions can remain physically present even after they are no longer visible to normal transactions. PostgreSQL’s <strong>VACUUM</strong> process is responsible for cleaning up such obsolete versions when it is safe to do so.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e752414750e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ PostgreSQL Internals — Part 1: Understanding PostgreSQL Architecture]]></title>
            <link>https://medium.com/@alamhamza873/postgresql-internals-part-1-understanding-postgresql-architecture-a03568b22560?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03568b22560</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 11:07:57 GMT</pubDate>
            <atom:updated>2026-07-15T11:07:57.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>PostgreSQL Cluster and Template Databases</h3><p>PostgreSQL is a database management system. When the PostgreSQL server program is running, we call it a <strong>PostgreSQL server instance</strong>.</p><p>A single PostgreSQL server instance can contain multiple databases. A collection of databases managed by a single PostgreSQL server instance is called a <strong>cluster</strong>.</p><p>All files related to a PostgreSQL cluster are stored inside a directory called <strong>PGDATA</strong>.</p><p>After creating a cluster, PostgreSQL provides some default template databases:</p><h3>Template0</h3><p>template0 is a default template database that contains the original database structure created during cluster initialization.</p><p>It is mainly used when restoring a database from a backup or when creating a database with a completely clean state. It should not be modified because PostgreSQL relies on it as a pristine template.</p><h3>Template1</h3><p>template1 works as a blueprint for creating new databases.</p><p>When you create a new database, PostgreSQL copies the structure of template1 by default. Any changes made to template1 (such as adding extensions or objects) will appear in newly created databases.</p><h3>PostgreSQL Database</h3><p>postgres is a default database created during PostgreSQL installation. It is a normal database that you can use for administration, testing, or any other purpose according to your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtDOqY7AaVOvErc9pxUzdw.png" /></figure><h3>System Catalog</h3><p>Metadata of all objects like tables, indexes, and functions is stored in a set of tables called the system catalog. Every database has tables, indexes, and functions that describe the objects of that database. Many system catalog tables can be the same across multiple databases.</p><h3>Schemas</h3><p>A schema is a namespace — you can think of it as a virtual directory — that holds a database’s objects in a logical order. If a user doesn’t create a schema of their own, PostgreSQL has its own default schemas.</p><h3>Public</h3><p>This is the default schema for user objects unless other settings are specified.</p><h3>Pg Catalog</h3><p>This is the schema used for catalog tables.</p><h3>Pg Toast</h3><p>This is for TOAST-related objects (I’ll describe what TOAST is below).</p><h3>Information Schema</h3><p>Every database system (PostgreSQL, MySQL, Oracle, SQL Server, etc.) stores metadata in its own internal system catalog. Since these internal catalogs have different table names and structures, the SQL standard defines information_schema as a common set of views. This allows developers to use standard SQL queries to retrieve metadata without learning each database&#39;s proprietary system catalog.</p><h3>Tablespace</h3><p>A tablespace is a logical name that maps to a physical directory in the file system where database data (tables and indexes) is stored in the form of pages. Unlike schemas, which are used only for the logical organization of database objects, tablespaces control physical storage location and are independent of schemas. The same tablespace can be used by multiple databases within the same PostgreSQL cluster. During cluster initialization, two tablespaces are created.</p><h3>Pg Default</h3><p>It’s located in the PGDATA/base directory and is used as the default tablespace until you explicitly define another location.</p><h3>Pg Global</h3><p>It’s located in PGDATA/global and is used to store system-level catalogs that are common to the whole cluster.</p><h3>Relation</h3><p>Despite their differences, tables and indexes have one thing in common: they consist of rows. This is self-evident for a table, but it’s equally true for an index — an index has a value that points to a row in another table, and this value is itself stored in row form. There are other objects that also consist of rows, like <strong>sequences</strong> and <strong>materialized views</strong>, so PostgreSQL uses the term “relation” for all of these object types. I know it’s a confusing term, but since the founders used it, we’ll use it throughout this article.</p><h3>Files and Forks</h3><p>All information related to a relation is stored across several different <strong>forks</strong>, each containing data of a particular type. A fork is represented by a single file, and it grows over time — when it hits 1 GB, PostgreSQL creates another file for that fork called a segment. You can change this size limit.</p><p>A single relation is represented by several different files on disk. Even a single table without any indexes can have three files, corresponding to the number of mandatory forks.</p><p>Each tablespace contains different subdirectories, and all objects belonging to the same tablespace live within them — even a database has its own subdirectory (except for pg_global).</p><h3>Main Fork</h3><p>This represents the actual data. It’s available for any relation, and its file name is denoted by a numeric ID, which is stored in the pg_class table.</p><h3>Initialization Fork</h3><p>The initialization fork exists only for unlogged tables (created by the user with the UNLOGGED clause) and their indexes. It&#39;s the <strong>empty initial image of that specific object</strong> — a fixed, clean template that normal operations never touch. Inserts and updates go to the <em>main</em> fork, and those operations are not written to the write-ahead log, which makes them fast but unrecoverable. If a crash happens, PostgreSQL deletes the other forks and overwrites the main fork with the initialization fork, resetting the table (and its indexes) to a clean, empty, usable state.</p><h3>The Free Space Map</h3><p>This keeps track of the available space within pages. Its volume shrinks as new rows are inserted and frees up when vacuum reclaims space. It’s the quickest way to find new space within pages to accommodate new data.</p><p>All files related to the free space map have the suffix FSM. These files aren&#39;t created until they&#39;re necessary — the fastest way to generate them is to vacuum a table. To speed up searches, the free space map uses a B-tree, which takes at least three pages.</p><p>The free space map is provided for both tables and indexes. However, an index can’t simply reuse arbitrary free space, because an index structure is a B-tree that relies on the insertion point to preserve sort order. So the free space map for an index only tracks pages that can genuinely be reused within that structure.</p><h3>Visibility Map</h3><p>This is the quickest way to determine whether a page needs to be vacuumed or frozen. For this purpose, it stores 2 bits for each page.</p><h3>All Visible (First Bit)</h3><p>Every row on this page is visible to all transactions, and there are no dead tuples that need cleaning.</p><h3>All Frozen (Second Bit)</h3><p>All rows on this page have already been frozen (their MVCC transaction IDs converted to FrozenTransactionId).</p><h3>Pages</h3><p>To facilitate I/O operations, all files are logically divided into pages. A page represents the minimum amount of data that can be written or read at once, and many of PostgreSQL’s internal algorithms are tuned around page-level processing.</p><p>The page size is usually 8 KB, but you can configure it to be larger — only at build time, before the instance is launched. Once an instance is running, it uses pages of the same size throughout; it’s impossible to create a tablespace with a different page size.</p><p>Regardless of which fork they belong to, all files are handled by the server the same way: pages are first loaded into a cache/buffer (where they can be read or updated by processes) and then flushed back to disk as needed.</p><h3>TOAST</h3><p>Each row must fit on a single page — there’s no way to continue a row onto the next page. To store long rows, PostgreSQL uses a mechanism called TOAST (The Oversized-Attribute Storage Technique).</p><p>TOAST relies on several strategies: you can move long attributes into a separate service table by slicing them into smaller “toasted” chunks, or you can compress them so the row fits on the same page — or do both.</p><h3>Processes and Memory</h3><p>The first process of a PostgreSQL instance is postgres, traditionally called the <strong>postmaster</strong>. It&#39;s responsible for starting the other processes — on Unix-like systems it uses the fork() system call — and for supervising them. If any backend crashes, the postmaster assumes shared memory may have been corrupted, so it terminates <strong>all</strong> backends and reinitializes the instance (recovering via WAL), rather than restarting just the failed one.</p><p>Because of its simplicity, this process model has been used by PostgreSQL from the very beginning, and there’s an ongoing discussion about replacing it with a thread model.</p><p>The current model has some significant drawbacks. Every new connection forks a new backend process. The fork itself is cheap thanks to copy-on-write — the real cost comes from what each backend <strong>privately accumulates afterward</strong>: its own catalog cache, its own work_mem allocations for sorts and joins, its own heap. This private state is duplicated across every backend, so RAM pressure grows badly as connections increase. With threads, PostgreSQL would instead be a single process containing many threads, all sharing one address space — so things like the catalog cache would exist <strong>once</strong> instead of once per connection, allowing far more connections with far less RAM.</p><p>There are 8 main processes that run on a PostgreSQL server.</p><h3>Startup</h3><p>Restores the system after a failure.</p><h3>Autovacuum</h3><p>Removes stale data from tables and indexes.</p><h3>WAL Writer (Write-Ahead Logging)</h3><p>This process runs after changes are made to a table. Those changes first go into buffer memory, and from there, the WAL writer writes them into WAL files on disk.</p><h3>Checkpointer</h3><p>This process runs after the WAL writer has written changes to WAL files, applying those changes to the actual data pages.</p><h3>Writer</h3><p>This process handles dirty pages — when you update data in buffer memory, that update exists in memory but not yet on disk, so the writer process flushes the buffer memory and writes the update to disk.</p><h3>Stats Collector</h3><p>This process gathers and saves information about queries that have run, such as statistics the query optimizer uses to make planning decisions.</p><h3>WAL Sender</h3><p>This process comes into play when you’re replicating your database. Suppose you have two servers — server 1 has the primary database, and you want to replicate it to server 2. When WAL writing starts, PostgreSQL creates a WAL sender process to send that data over the network to the replica server.</p><h3>WAL Receiver</h3><p>This process receives the data coming from the WAL sender.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03568b22560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Moment a Machine Stops Memorizing and Starts Thinking Deep Learning, Part 1]]></title>
            <link>https://medium.com/@alamhamza873/the-moment-a-machine-stops-memorizing-and-starts-thinking-deep-learning-part-1-5d11b6d2bd6b?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d11b6d2bd6b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 07:59:59 GMT</pubDate>
            <atom:updated>2026-06-18T07:59:59.510Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning is being used increasingly in almost every aspect of modern society, from web search engines and content filtering systems to email spam detection. It is also widely used in consumer products such as cameras and smartphones for object detection and recognition. Many of these applications rely on a class of techniques known as <strong>deep learning</strong>.</p><p>Traditional machine learning techniques had limitations when working directly with raw data. In many cases, engineers had to manually design and extract features that would help the machine understand the data. For example, image pixels needed to be transformed into meaningful numerical representations before they could be processed effectively.</p><p><strong>Representation learning</strong> is a collection of methods that enables a model to automatically learn useful features directly from raw data. Instead of relying on manually engineered features, the model discovers the most relevant patterns on its own.</p><p>Deep learning is a form of representation learning that uses multiple layers of processing. Each layer learns increasingly complex representations of the input data:</p><ul><li><strong>First layer:</strong> Detects simple features such as edges and lines.</li><li><strong>Second layer:</strong> Combines edges into small patterns known as motifs.</li><li><strong>Third layer:</strong> Combines motifs into larger and more meaningful object parts.</li><li><strong>Deeper layers:</strong> Assemble object parts into complete objects, allowing the network to recognize items such as cars, dogs, or houses.</li></ul><h4>Supervised Learning</h4><p>Supervised learning is a type of machine learning, whether deep learning is used or not. Suppose we want to build a system that classifies images of houses, cars, and pets. To achieve this, we need a large dataset containing images that are already labeled with their correct categories.</p><p>These labeled images are fed into the model, which produces an output score representing its prediction. Initially, the model’s predictions are mostly inaccurate because it has not yet learned the relationship between the input data and the correct labels.</p><p>To train the model, we define an <strong>objective function</strong>, also known as a <strong>loss function</strong>, which measures how wrong the model’s predictions are. The goal of training is to minimize this loss.</p><p>The model contains parameters called <strong>weights</strong>, which are numerical values that control how inputs are transformed into outputs. Modern neural networks may contain millions or even billions of weights.</p><p>To improve its predictions, the model computes a <strong>gradient vector</strong>, which indicates how the loss changes with respect to each weight. The weights are then updated in the opposite direction of the gradient because we want to reduce the loss. If increasing a particular weight causes the loss to increase, the optimization algorithm will decrease that weight instead.</p><p>You can think of the loss function as a hilly landscape. High points represent large errors, while the lowest point represents the minimum possible error. The gradient acts like a compass, indicating the direction the model should move to reach lower loss values.</p><h4>Stochastic Gradient Descent (SGD)</h4><p>In practice, many machine learning practitioners use <strong>Stochastic Gradient Descent (SGD)</strong> for optimization.</p><p>During training, the model receives input data, produces predictions, calculates the loss, and estimates the gradient. Rather than computing the gradient using the entire dataset before every update, SGD uses either a single training example or a small batch of examples to estimate the gradient and immediately update the weights.</p><p>This process is repeated many times until the loss stops decreasing and the model converges to a good solution.</p><p>The primary advantage of SGD is efficiency. For example, if a dataset contains one million training examples, calculating the exact gradient using the entire dataset before every update would be computationally expensive. SGD uses a small random subset of the data, allowing much faster updates while still moving approximately in the correct direction.</p><h4>Multilayer Networks and Data Representation</h4><p>Before data enters a neural network, it may be represented in a form where different classes are difficult to separate. The hidden layers of a neural network progressively transform the data into more useful representations.</p><p>For example, imagine images belonging to two classes represented as mixed blue and green points. As data passes through successive hidden layers, the network reshapes the representation so that the two classes become easier to separate.</p><p>This ability to automatically learn useful representations is one of the key strengths of deep learning.</p><h4>Inside a Convolutional Neural Network (CNN)</h4><p>Consider a CNN that receives an image of a Samoyed dog as input.</p><p>The network processes the image layer by layer:</p><ol><li>Early layers detect simple features such as edges and color transitions.</li><li>Intermediate layers identify textures, shapes, and patterns.</li><li>Deeper layers combine these patterns into meaningful object parts such as ears, eyes, or fur.</li><li>The final layers use these learned features to recognize the complete object.</li></ol><p>The network must achieve two goals simultaneously:</p><ul><li><strong>Selectivity:</strong> Distinguish a Samoyed from a white wolf, even though they look very similar.</li><li><strong>Invariance:</strong> Ignore irrelevant changes such as lighting conditions, viewing angles, position, or whether the dog is sitting or standing.</li></ul><p>These competing objectives are known as the <strong>selectivity–invariance dilemma</strong>.</p><h4>Kernel Methods Before Deep Learning</h4><p>Before deep learning became dominant, many machine learning systems relied on <strong>kernel methods</strong>.</p><p>A kernel can be thought of as a function that measures how similar two data points are. One of the most popular kernels is the <strong>Gaussian Kernel</strong>.</p><p>Sometimes data cannot be separated by drawing a straight line in its original feature space. Kernel methods address this problem by implicitly mapping the data into a higher-dimensional space where separation becomes easier.</p><p>The Gaussian kernel does not explicitly compute these higher-dimensional coordinates. Instead, it uses a mathematical trick known as the <strong>kernel trick</strong> to obtain the same result without performing the expensive transformation directly.</p><p>Although kernel methods achieved impressive results, they had an important limitation: they depended heavily on carefully engineered features. Designing these features often required significant domain expertise and human effort.</p><p>Deep learning largely removes this dependency. Neural networks automatically learn useful features directly from raw data. Early layers learn edges and colors, intermediate layers learn textures and shapes, and deeper layers learn high-level concepts. As a result, the network learns what information should be preserved and what information can be ignored for the task at hand.</p><h4>Backpropagation to train multilayer architectures</h4><p>From the early days of pattern recognition, researchers wanted to replace hand-engineered features with multilayer networks that could automatically learn useful features from data. However, they did not have an efficient way to train the many weights in these networks. They knew that the weights should be adjusted to reduce the loss function, but they needed a practical method to determine how much each weight contributed to the error. In the 1970s and 1980s, researchers discovered that backpropagation could efficiently compute these contributions (gradients), and stochastic gradient descent could then use those gradients to update the weights. This made training multilayer neural networks practical. the loop look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vo5CdPOV_HtLc2Yn5XJWqA.png" /></figure><h4>Activation Function: ReLU (Rectified Linear Unit)</h4><p>ReLU is an activation function applied after each neuron output W⋅x+bW·x + bW⋅x+b. It passes the value directly if it is positive and outputs zero if it is negative. This introduces non-linearity into the network, which is necessary because without activation functions, stacked layers would behave like a single linear equation and the model would not learn complex patterns like edges, shapes, or objects.</p><p>Before ReLU, activation functions like Sigmoid and Tanh were used. They also introduce non-linearity, but they suffer from the <strong>vanishing gradient problem</strong>. During backpropagation, the gradients become very small as they pass through many layers, so early layers receive almost zero updates. This makes deep networks difficult to train.</p><p>ReLU solves this problem by allowing gradients to pass through unchanged for positive values, so the gradient does not shrink as much during backpropagation. This helps the network learn faster and makes deep neural networks practical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d11b6d2bd6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is AI Replacing Our Ability to Think?]]></title>
            <link>https://medium.com/@alamhamza873/is-ai-replacing-our-ability-to-think-53ce469e7931?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ce469e7931</guid>
            <category><![CDATA[cognitive-science]]></category>
            <category><![CDATA[human-intelligence]]></category>
            <category><![CDATA[ai-and-society]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 08:01:12 GMT</pubDate>
            <atom:updated>2026-01-13T08:01:12.109Z</atom:updated>
            <content:encoded><![CDATA[<p>First, let’s talk about <strong>intelligence</strong>. What is a simple definition of intelligence?</p><p>I’d like to share what the French psychologist <strong>Alfred Binet</strong> said about intelligence. According to him, <strong>intelligence cannot be measured — it can only be classified</strong>.</p><p>He identified <strong>four important components of intelligence</strong>, which are:</p><ol><li><strong>Reasoning</strong></li><li><strong>Judgment</strong></li><li><strong>Memory</strong></li><li><strong>Power of Abstraction</strong></li></ol><h3>Reasoning</h3><p>𝗥𝗲𝗮𝘀𝗼𝗻𝗶𝗻𝗴 means using information to come to a conclusion or make a decision.<br>For example, you see dark clouds coming, and you know that when dark clouds appear, there is a chance of rain. You use this information to decide whether or not to go home and take an umbrella.<br>If you decide to go home and take an umbrella, that conclusion is based on your reasoning — using the information you have to make a thoughtful decision.</p><h3><strong>Judgment</strong></h3><p>𝗝𝘂𝗱𝗴𝗺𝗲𝗻𝘁 is a key component of intelligence — you could call it common sense or street smarts. Let me give you an example.<br>A highly intelligent person can easily solve a math problem, but a person with good judgment knows <strong>when to speak, when to take action, and how to handle a complex situation wisely.</strong></p><h3>Memory</h3><p>𝗠𝗲𝗺𝗼𝗿𝘆 is the ability to encode, store, and recall information and use it when it’s necessary. Memory is also a very essential part of learning.</p><p>Let me explain what encoding means. Your brain does not store information in its raw form; it is converted into a mental code. A mental code can be a pattern of neurons that represents that information. There are different types of encoding.</p><ol><li><strong>Visual Encoding (Picture)</strong></li><li><strong>Acoustic (sound)</strong></li><li><strong>Semantic (meaning)</strong></li></ol><p>𝗩𝗶𝘀𝘂𝗮𝗹 𝗲𝗻𝗰𝗼𝗱𝗶𝗻𝗴 is when you remember something by using pictures — for example, remembering your friend by their face.</p><p>𝗔𝗰𝗼𝘂𝘀𝘁𝗶𝗰 𝗘𝗻𝗰𝗼𝗱𝗶𝗻𝗴<strong> </strong>is happen when you try to remember by any sound like you try to remember song by its lyrics.</p><p>𝗦𝗲𝗺𝗮𝗻𝘁𝗶𝗰 𝗘𝗻𝗰𝗼𝗱𝗶𝗻𝗴 happens when you try to remember something by its meaning — for example, knowing that an apple is a fruit.</p><p>One more important thing is that when you learn something through your senses, your brain receives signals. Then, your brain cells — neurons — trigger signals from one neuron to another. This process involves <strong>neurotransmitters</strong>.</p><p>Let me explain how it works. First, one neuron triggers a signal, which travels to another neuron and eventually reaches a junction called a <strong>synapse</strong>. When the signal reaches the synapse, it releases neurotransmitters. This process continues, and with focus and practice on a particular task, it becomes stronger and communication between neurons becomes easier.</p><p>There are a few types of neurotransmitters:</p><ul><li><strong>Dopamine</strong> → involved in reward, motivation, movement, and learning</li><li><strong>Serotonin</strong> → regulates mood, sleep, appetite, and memory</li></ul><h3>Power Of Abstraction</h3><p>Abstraction has many definitions, but in the context of intelligence, it means the ability to understand the complex structure behind a simple process. For example, when you type “google.com,” if you know what happens after you press Enter — like where your request first goes, what DNS does, and how the system processes it — you are demonstrating intellectual abstraction.</p><p>Now, let’s talk about AI. I have already described what intelligence is and how it can be categorized. Now, let’s discuss how AI might affect our intelligence. The argument that we are becoming less intelligent is driven by several factors. One of the most interesting involves the <strong>Flynn effect</strong>, which is the observation that the IQ of new generations tends to be higher and stronger than that of previous generations. However, in recent years, this effect has slowed — or in some cases, even reversed.</p><p>In the UK, James Flynn himself showed that the average IQ of 14-year-old children dropped by 2 points between 1980 and 2008. As you can see, this trend had already begun before tools like ChatGPT emerged. Now, you can imagine how this effect could accelerate with the increasing use of AI.</p><h3>MIT STUDY</h3><p>According to an MIT study, if you rely excessively on AI, you could become a victim of <strong>“Cognitive Autopilot.”</strong> What is this? In such circumstances, you may lose your critical thinking skills.</p><p>Another point is that humans are better than AI at <strong>Bayesian reasoning</strong>. What is Bayesian reasoning? It means updating your decisions based on new evidence. For example, if you hear a sound, you might estimate there is a 60% chance it is the wind and a 40% chance it is something else. If you hear the sound again, but louder this time, you update your probabilities: maybe now it is 40% wind and 60% something else. Finally, if you hear barking, you can conclude it is most likely a dog. This process of updating your beliefs with new evidence is called Bayesian reasoning.</p><h3>Christopher Dede</h3><p>He is a senior research fellow at the Graduate School of Education. According to him, AI should be used like an <strong>“Owl of Wisdom.”</strong> Why specifically an owl? There is a context: in Greek mythology, Athena, the Goddess of Wisdom, is often portrayed with an owl on her shoulder.</p><p>According to him, if you use AI just to complete your essays or job applications, you risk losing your critical thinking skills — and potentially even your job. Instead, you should use AI like the Owl of Wisdom: engage with it thoughtfully, question it, and try to reason through problems yourself. If you only ask AI to complete tasks without thinking, there is a 99% chance you will weaken your ability to think critically.</p><p>That’s the end of this article. I hope you enjoyed reading it and now have a better understanding of the potential drawbacks of misusing AI. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ce469e7931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kashmir — Heaven on Earth]]></title>
            <link>https://medium.com/@alamhamza873/kashmir-heaven-on-earth-eca53cfb2441?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eca53cfb2441</guid>
            <category><![CDATA[arang-kel]]></category>
            <category><![CDATA[kashmir]]></category>
            <category><![CDATA[islamabad]]></category>
            <category><![CDATA[maree]]></category>
            <category><![CDATA[kashmir-tour]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 19:00:21 GMT</pubDate>
            <atom:updated>2025-06-02T19:00:21.129Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kashmir — Heaven on Earth</h3><p>Hi friends, today I just want to tell you my story about how I visited <strong>Kashmir</strong> for the first time in my life. So, without any delay, let’s get started!</p><h3>Planning</h3><p>So, the story starts exactly 4–5 months ago when I joined a new company. There, I talked with a friend and colleague. At that time, I told him that I wanted to go on a trip to the northern areas of <strong>Pakistan</strong>. He was also very interested and said, “I will go with you.” And the conversation ended there — no further discussion.</p><p>After about 3 months, I brought it up again and said, “Let’s find a travel agency that can help us plan the trip at a reasonable price.” He found one agency, and I agreed, saying, “Yes, this is a good package for Kashmir. Let’s go next month.”</p><p>But the main challenge was getting leave from the office. Thankfully, my manager was very supportive, and I got my leave approved. My friend’s leave was also granted.</p><p>So, this was our planning phase for the journey.</p><h3>Travel by Sleeping Bus</h3><p>After planning everything, we booked a <strong>sleeping bus</strong> to travel from Karachi to Islamabad. At first, my friend told me not to book a sleeping bus because it doesn’t have enough space for both of us. But since it was my first time traveling like this, I really wanted to experience it — so I booked it anyway.</p><p>Exactly on <strong>Friday, 11th (2025)</strong>, we started our journey. As expected, the main issue was that we didn’t get enough space to sleep comfortably. But this, too, became a memorable part of our adventure.</p><p>During the journey, we saw many beautiful places. For me, it felt like a dream come true. Coming from a middle-class family, we never had the chance to travel outside our city. You can imagine — I’m 25 years old, and this was my very first trip to Kashmir.</p><p>So yes, it was truly a dream that Allah fulfilled for me — <strong>Alhamdulillah</strong>.</p><p>One more thing I realized: when you travel, the bubble you live in starts to break. You begin to see the world from a new perspective.<br> And that’s how my journey in the sleeping bus began.</p><h3>Reached In Islamabad</h3><h3>From Karachi to Islamabad — A New Perspective</h3><p>When I reached Islamabad, I realized how underdeveloped my city — <strong>Karachi</strong> — really is. Karachi is considered the economic hub of Pakistan, yet there are very few proper places to visit, no greenery, and many other problems. It was a <strong>painful truth</strong> I had to accept after seeing Islamabad’s clean, organized environment.</p><p>When we arrived at the hotel in Islamabad, I was impressed. The room had two beds, a clean bathroom with a good shower, and many other comforts. For me, it was luxury — something I had never experienced before. I know I paid for it, but it made me realize that sometimes, spending money on yourself <strong>is truly worth it</strong>.</p><p>After freshening up, my friend and I went for a walk. That’s when I noticed another big difference between Karachi and Islamabad. Karachi is a lively, open city that stays awake at night — you’ll find shops open, people out shopping or eating, and a lot of hustle and bustle. But Islamabad is the opposite. It feels dull and quiet at night, with very few people on the streets. I’m just sharing this based on my personal experience.</p><p>After our walk, we returned to the hotel. Our tour guide informed us, “Please be ready by <strong>5 AM sharp</strong>, we’ll begin our journey to Kashmir.” We packed our bags, checked out, and stepped outside — our tour bus was already waiting.</p><h3>Islamabad to Kashmir — A Dream With a Twist</h3><p>We started our journey from Islamabad to Kashmir early in the morning. But here’s a twist — <strong>if you’re visiting this route for the first time, make sure to carry motion sickness medicine.</strong> The road is beautiful but full of curves, and yes, it <strong>can really make you nauseous</strong>. I threw up <strong>twice</strong>, and it wasn’t easy, especially since this was my first time traveling such a mountainous route.</p><p>But despite the discomfort, the journey was breathtaking. The views were unreal — <strong>majestic mountains</strong>, <strong>waterfalls</strong>, and endless natural beauty all around. It truly felt like a <strong>life-changing experience</strong>.</p><p>Let me show you some pictures so you can see just how beautiful it really was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*f8fTMf_PRLa6F8Bs1FwuNA.jpeg" /><figcaption><strong>Arang Kel</strong></figcaption></figure><h3>Arang Kel — A View Worth the Climb</h3><p>This is <strong>Arang Kel</strong>, and it’s the most breathtaking view I’ve seen in my entire life so far.</p><p>Before reaching here, we had to <strong>climb a mountain</strong> — and trust me, if you’re not fit and healthy, it’s one of the most difficult things you’ll ever do. As I was climbing, I realized how easy it seemed for the <strong>local people</strong>. During the climb, I saw a young boy effortlessly walking up the mountain. I called out to him and asked, “Where do you live?” He smiled and replied, “I live at the top — where you’re headed.”</p><p>I was shocked. He told me he climbs up and down <strong>multiple times a day</strong> without any rest. That moment made me realize how <strong>physically strong and adapted</strong> the locals are to this terrain.</p><p>When I finally reached the top, I understood — it was <strong>totally worth it</strong>. The view was absolutely stunning, like something out of a dream.</p><p>I then ordered a cup of <strong>Kashmiri tea</strong>, and it was incredibly delicious. The guy who served it was around the same age as me but extremely <strong>respectful and humble</strong>. I asked him, “Why is this tea so good?” He told me they use a special type of tea leaves (<strong>patti</strong>) that grow only in the mountains of Kashmir. That’s what makes the flavor so unique.</p><p>Unfortunately, we couldn’t stay the night in Arang Kel and had to return to <strong>Sharda</strong>, but that too is a <strong>very beautiful place</strong>.</p><p>Now, let me show you some pictures of Sharda where we stayed — you’ll see how magical it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*skHriadK9I9AN5qgyrfXWQ.jpeg" /><figcaption><strong>Shardha</strong></figcaption></figure><h3>Where We Stayed</h3><p>So this is where we stayed — and honestly, the view was absolutely <strong>amazing</strong>. I truly <strong>miss that one week</strong>; it was one of the most peaceful and refreshing times of my life.<br> I know I couldn’t describe every single moment of the trip, but I hope this gives you a good idea of what I experienced and what I wanted to share with you.</p><h3>Conclusion</h3><p>The whole purpose of this article is to remind you that <strong>sometimes, you just need to take a break</strong> and explore the beauty of nature. It helps you realize how <strong>incredible this world truly is</strong> — something we often forget in our busy lives.</p><p>Thanks for reading. 🌿</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eca53cfb2441" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Process Architecture In 2025]]></title>
            <link>https://medium.com/@alamhamza873/postgresql-process-architecture-in-2025-0b71309e9690?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b71309e9690</guid>
            <category><![CDATA[background-process]]></category>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 06:33:16 GMT</pubDate>
            <atom:updated>2025-02-06T06:35:21.977Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi programmers Recently, many of us tend to overlook the importance of databases — how critical they are, how they work internally, how queries are processed, and how databases handle concurrent requests.</p><p>In this article, let’s dive deep into these topics. I’ll use <strong>PostgreSQL</strong> as an example to explain these concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pr9EdzAhstv9VJz5Mga2xw.jpeg" /></figure><h3>What is PostgreSQL?</h3><p><strong>PostgreSQL</strong> is a powerful database management system that allows you to store and retrieve data efficiently. It runs on a server, which is referred to as the <strong>PostgreSQL Server</strong> or <strong>instance</strong>.</p><p>A single PostgreSQL instance can host multiple databases, and the collection of these databases within an instance is called a <strong>cluster</strong>.</p><h3>How Does a Cluster Work?</h3><p>Before using <strong>PostgreSQL</strong>, you need to initialize a <strong>cluster</strong>. This process creates a directory called <strong>PGDATA</strong>, where all the cluster’s files are stored.</p><h3>What Happens After Initialization?</h3><p>After initialization, three databases are automatically created within the cluster.</p><h3>1. Template-0</h3><p>This database stores all the backups, so you should avoid making any updates or changes to it.</p><h3>2. Template-1</h3><p>This database is used as a template for all new databases created. Why do new databases use this database as a template? Because it provides a standard configuration for all newly created databases.</p><h3>3. Postgres</h3><p>This is a regular database that you can freely use to store and retrieve data, as well as create additional tables. This database also uses <strong>Template-1</strong> as its template.</p><h3>What Is the System Catalog?</h3><p>The <strong>system catalog</strong> is a collection of tables that store metadata about the database, such as information about tables, functions, and views. Every database has these types of tables, which contain detailed information about the tables, functions, indexes, and other database objects. These tables have a primary key called <strong>OID</strong>, which is a 32-bit integer.</p><h3>What is a Relation in PostgreSQL?</h3><p>In PostgreSQL, the term <strong>“Relation”</strong> comes from <strong>relational database theory</strong>, which strictly defines a relation as a table that holds structured data. However, in PostgreSQL, this term can be a bit confusing. The creator of PostgreSQL, <strong>Michael Stonebraker</strong>, used the term “Relation” in a broader sense. It refers to any database object that contains rows, such as <strong>tables</strong>, <strong>indexes</strong>, and <strong>sequences</strong>. Essentially, you can use the term “relation” whenever there are rows in any database object.</p><h3>How Do Indexes Work Internally?</h3><p>This is a fascinating topic because many developers know that when you apply an index to a column and use that column in a query, it helps retrieve data faster. However, most people don’t know how the database handles this internally.</p><p>In a database, every table is stored in <strong>heap memory</strong> (an unsorted collection of files that contain rows). By default, the data is unsorted. So, when you run a retrieval query without applying an index to any column, the database has to scan through all the rows to find the relevant data.</p><pre>SELECT * FROM employees WHERE age = 30;</pre><p>In this example, the database will have to read the entire table to find employees because the data is unsorted. However, when you apply an index (for example, on the <strong>age</strong> column), the index will store the age values in a different, optimized structure. This allows the database to access the data more efficiently. Let’s take a look at how the index stores the age values in a sorted way:</p><pre>         (30)<br>        /    \<br>   (25)      (35)<br>   /  \       /  \<br>[2, TID2]  [1, TID1] [4, TID4]  [3, TID3]</pre><pre>Indexed Value (age) Tuple ID (TID) (Pointer to Heap Table)<br>25                  TID (Row 2)<br>30                  TID (Row 1), TID (Row 4)<br>35                  TID (Row 3)</pre><p>So, as you can see in this example, when you apply an index to the <strong>“age”</strong> column, the index will store the age values in a sorted order, along with pointers to the corresponding rows, making it easy to retrieve data quickly. However, on the flip side, indexes can be costly when it comes to <strong>insertions</strong>. This is because, whenever the database updates a value, it also has to update the index table. As a result, insertions become slower due to the extra overhead of maintaining the index.</p><h3>Conclusion</h3><p>The conclusion of this article is that many developers are unaware of how databases work internally, and this is a critical aspect that many tend to overlook. That’s why I wrote this article — to help you easily understand some important concepts that are essential for working with databases effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b71309e9690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI is destroying your ability to think]]></title>
            <link>https://medium.com/@alamhamza873/ai-is-destroying-your-ability-to-think-fda5db42d64e?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fda5db42d64e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[critical-thinking]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 10:44:59 GMT</pubDate>
            <atom:updated>2025-01-02T10:44:59.998Z</atom:updated>
            <content:encoded><![CDATA[<p>As a software engineer, I can confidently say that AI significantly impacts our critical thinking skills. Paul Graham, an American computer scientist and writer, recently tweeted about the percentage of code written by AI. According to him, while the overall percentage is below 40%, it jumps to around 90% for young programmers, especially when it comes to checking and correcting mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wo4cssiYrtrwFutxUoIpgA.png" /></figure><p>In my opinion, the percentage is much higher, especially in the early days of a programmer’s career. Previously, solving problems independently helped programmers improve their critical thinking skills. However, this is no longer the case for many young programmers today, as they are becoming increasingly dependent on AI.</p><h3>What Will Happen If Humans Become Totally Dependent on AI?</h3><p>Have you ever seen the movie <em>WALL-E</em>? In this film, humans are living on a giant spaceship because Earth has become uninhabitable due to air pollution. On the spaceship, people are entirely dependent on AI, which makes all their life decisions. Toward the end of the movie, life starts to return to Earth, and humans want to go back. However, the AI resists this idea out of fear that if humans return to Earth, they will regain control of their own decisions.</p><p>While <em>WALL-E</em> is a sci-fi example, it raises an important point: if our consciousness becomes entirely dependent on AI, it could diminish our autonomy and even our significance in the world.</p><h3>AI’s Impact on Human Decisions and Behavior</h3><p>According to an article on <em>nature.com</em>, a study shows the impact of AI on human life. The study was conducted among universities in Pakistan and China, revealing that students are becoming overly dependent on AI. The results show a 68.9% increase in laziness, 68.6% increase in privacy and security issues, and a 27.7% decline in decision-making abilities. As you can see, these statistics are quite concerning. If this trend continues, we can only imagine how much human capabilities will be affected in the future.</p><h3>What’s the Solution?</h3><p>In my perspective, I believe the first thing we can do is take back the small tasks that GPT and other AIs do for us and continue doing them ourselves. I’m not suggesting that we completely remove AI from our lives — obviously, that may not be possible — but we can take small steps to handle easy tasks ourselves and not become overly dependent on AI.</p><h3><strong>Conclusion</strong></h3><p>The motive of this entire article is to raise concerns about the use of AI in our lives, highlighting how we may lose control over our work decisions, become too weak to make decisions, and become lazy. So, let’s try to prevent this. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda5db42d64e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rise of Linux]]></title>
            <link>https://medium.com/@alamhamza873/the-rise-of-linux-a0fca46b4b1a?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0fca46b4b1a</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[linus-torvalds]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 06:01:00 GMT</pubDate>
            <atom:updated>2024-12-10T06:01:00.474Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is all about the focus and determination of one man who created a unique operating system that has helped thousands of people in their daily lives. Today, approximately 71.85% of mobile devices run on Android, which is based on Linux. So, let’s begin this journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wogxweHe9ErRaTfAcp4mbA.jpeg" /></figure><h3>How This All Started</h3><p>This story begins in the early 1990s when a computer science student at the University of Helsinki in Finland started working on a side project. His name was Linus Torvalds, and now you can understand why the operating system is called Linux — it’s a combination of his first name and the “x” from the UNIX operating system.</p><p>Linus wanted to create a system that was easy to use and affordable for everyone because, at that time, operating systems were expensive. So, let’s dive into the story of the man behind it all.</p><h3>Who is Linus Torvalds?</h3><p>As you already know, Linus Torvalds was a computer science student at the University of Helsinki in Finland. However, I want to share more about him, so let’s start from the beginning.</p><p>Linus Torvalds was born on December 28, 1969, in Helsinki, Finland. (Fun fact: Helsinki is the capital of Finland.) At the age of 10, he developed an interest in computer programming on his grandfather’s Commodore VIC-20.</p><p>You might be wondering, what is a Commodore? The VIC-20 (known as the VC-20 in Germany and the VIC-1001 in Japan) was an 8-bit home computer sold by Commodore Business Machines. It was announced in 1980, roughly three years after Commodore’s first personal computer.</p><p>When Linus was in university, he purchased his first personal computer (PC). However, after using it for some time, he became dissatisfied with how PCs operated. He preferred the UNIX operating system that he was using on the university’s computers.</p><p>And that’s a brief introduction to the creator of Linux.</p><h3>Born Of Linux</h3><p>After a disappointing experience with his PC, and following months of hard work and determination, Linus Torvalds posted a message on the internet announcing that he had created an operating system that was free to download.</p><p>At that time, it was common practice for developers to make their code open source, allowing others to use and modify it according to their needs. This significant moment occurred in 1991. Once the open-source code was made available, many developers joined forces with Linus to refine and stabilize the Linux operating system.</p><p>Finally, in 1994, the first Linux kernel (the core code), version 1.0, was officially released.</p><h3>Linus Torvalds Is Not Happy</h3><p>As you know, Linus Torvalds created Linux as an open-source project. Occasionally, when someone made changes to the code repository that Linus didn’t agree with, he would send strongly worded, sometimes even harsh, emails to them.</p><p>It might sound extreme, but Linus had a point. Linux is not a casual project where lazy coding or bad practices can be tolerated. His strict approach ensured the project’s quality and integrity. So, if someone committed poorly written or careless code, it’s no surprise that Linus would get upset.</p><h3>What Linux have and Windows Don&#39;t</h3><p>Before we dive in, I just want to share something: <em>Linux is an amazing software, and Windows also has its strengths.</em></p><p>As a programmer, I often work on servers, and as you know, many servers run on Linux (except for IIS, which is specific to Windows). One significant advantage of Linux is that it comes with pre-installed compilers like C++ and Python, saving you time and effort.</p><p>Additionally, Linux doesn’t require a system restart after updating software, which is a huge convenience. Being open source, Linux also allows you to customize programs according to your needs.</p><p>Lastly, Linux is fantastic for automation. For instance, you can automate tasks by writing simple Python scripts — whether it’s setting up an auto-reply for your emails or managing other repetitive tasks. The possibilities are endless!</p><h3>Conclusion</h3><p>The conclusion of this article is that Linux is better than Windows in terms of speed and flexibility. If you are a programmer, you should definitely consider using Linux.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0fca46b4b1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Large Files in Chunks from React to a Node.js Express Backend]]></title>
            <link>https://medium.com/@alamhamza873/uploading-large-files-in-chunks-from-react-to-a-node-js-express-backend-14b553307cea?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b553307cea</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[large-file-upload]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 15:09:35 GMT</pubDate>
            <atom:updated>2024-10-26T15:09:35.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi friends! As a developer, you often face scenarios where you need to upload large files. Uploading these can be challenging due to their size, and finding the right method can be tricky. Today, I’ll show you an easy and effective way to upload large files. Let’s dive in and start coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSSSuBASAzNAryupF-ZxQQ.jpeg" /></figure><p>Ok first let&#39;s set a backend for uploading large files and then we will go to the UI side.</p><p>first, you must create a new directory called <strong>“Nodebackend” </strong>and open cmd in this folder, and write these commands.</p><pre>npm install express multer</pre><p>This command will install the Express framework for Node.js, along with Multer — a middleware module for Node.js that simplifies file uploads. After this, you’ll just need to write the code, so let’s get started!</p><pre>const express = require(&#39;express&#39;);<br>const multer = require(&#39;multer&#39;);<br>const path = require(&#39;path&#39;);<br>const app = express();<br><br>// Set storage engine using Multer<br>const storage = multer.diskStorage({<br>    destination: &#39;./uploads/&#39;,<br>    filename: (req, file, cb) =&gt; {<br>        cb(null, file.fieldname + &#39;-&#39; + Date.now() + path.extname(file.originalname));<br>    }<br>});<br><br>// Initialize upload variable<br>const upload = multer({<br>    storage: storage<br>}).single(&#39;file&#39;);<br><br>// POST route to handle file upload<br>app.post(&#39;/upload&#39;, (req, res) =&gt; {<br>    upload(req, res, (err) =&gt; {<br>        if (err) {<br>            return res.status(500).json({ message: &#39;File upload failed&#39; });<br>        }<br>        res.status(200).json({ message: &#39;File uploaded successfully&#39; });<br>    });<br>});<br><br>// Start server<br>app.listen(5000, () =&gt; {<br>    console.log(&#39;Server started on port 5000&#39;);<br>});</pre><p>Now, in your root directory, create a folder named uploads and a file called upload.js, then paste the code there. In this code, I first set up Multer to process the file request and save it in the destination folder. Now, let’s move to the front end. First, create a React project using this command:</p><pre>npx create-react-app my-app.</pre><p>After the setup, you need to install a few additional packages: <strong>Axios</strong> for making API requests, <strong>react-icons</strong> to add a file upload icon, and <strong>styled-components</strong> for styling the components. You can use the following commands to install these packages:</p><pre>npm install axios<br>npm install react-icons<br>npm install styled-components</pre><p>after this, you just have to create a file “<strong>FileUpload</strong>.js” and paste this code like this.</p><pre>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br>import styled from &#39;styled-components&#39;;<br>import { FaCloudUploadAlt } from &#39;react-icons/fa&#39;;<br><br>const PageContainer = styled.div`<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    height: 100vh;<br>    background-color: #f0f2f5;<br>`;<br><br>const Container = styled.div`<br>    display: flex;<br>    flex-direction: column;<br>    align-items: center;<br>    padding: 20px;<br>    background-color: #ffffff;<br>    border-radius: 8px;<br>    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);<br>    width: 400px;<br>`;<br><br>const Heading = styled.h2`<br>    font-size: 1.5rem;<br>    color: #333;<br>`;<br><br>const FileInput = styled.input`<br>    display: none;<br>`;<br><br>const FileLabel = styled.label`<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    background-color: #007bff;<br>    color: white;<br>    padding: 10px 20px;<br>    font-size: 1rem;<br>    border-radius: 4px;<br>    cursor: pointer;<br>    margin-bottom: 20px;<br>    transition: background-color 0.3s ease;<br><br>    &amp;:hover {<br>        background-color: #0056b3;<br>    }<br>`;<br><br>const UploadButton = styled.button`<br>    background-color: #28a745;<br>    color: white;<br>    padding: 10px 20px;<br>    border: none;<br>    border-radius: 4px;<br>    cursor: pointer;<br>    font-size: 1rem;<br>    transition: background-color 0.3s ease;<br><br>    &amp;:hover {<br>        background-color: #218838;<br>    }<br>`;<br><br>const ProgressContainer = styled.div`<br>    width: 100%;<br>    background-color: #e9ecef;<br>    border-radius: 4px;<br>    margin-top: 10px;<br>`;<br><br>const ProgressBar = styled.div`<br>    width: ${props =&gt; props.width}%;<br>    height: 8px;<br>    background-color: #007bff;<br>    border-radius: 4px;<br>    transition: width 0.4s ease;<br>`;<br><br>const FileUpload = () =&gt; {<br>    const [file, setFile] = useState(null);<br>    const [uploadPercentage, setUploadPercentage] = useState(0);<br><br>    const onFileChange = (e) =&gt; {<br>        setFile(e.target.files[0]);<br>    };<br><br>    const onFileUpload = async () =&gt; {<br>        if (!file) {<br>            alert(&quot;Please select a file first!&quot;);<br>            return;<br>        }<br><br>        const formData = new FormData();<br>        formData.append(&#39;file&#39;, file);<br><br>        try {<br>            const res = await axios.post(&#39;http://localhost:5000/upload&#39;, formData, {<br>                headers: {<br>                    &#39;Content-Type&#39;: &#39;multipart/form-data&#39;<br>                },<br>                onUploadProgress: progressEvent =&gt; {<br>                    const percentCompleted = Math.round(<br>                        (progressEvent.loaded * 100) / progressEvent.total<br>                    );<br>                    setUploadPercentage(percentCompleted);<br>                }<br>            });<br><br>            console.log(res.data);<br>            alert(&#39;File uploaded successfully&#39;);<br>            setUploadPercentage(0); // Reset progress bar<br>        } catch (err) {<br>            console.error(err);<br>            alert(&#39;Error uploading file&#39;);<br>        }<br>    };<br><br>    return (<br>        &lt;PageContainer&gt;<br>            &lt;Container&gt;<br>                &lt;Heading&gt;File Upload with Progress&lt;/Heading&gt;<br>                &lt;FileInput type=&quot;file&quot; id=&quot;file&quot; onChange={onFileChange} /&gt;<br>                &lt;FileLabel htmlFor=&quot;file&quot;&gt;<br>                    &lt;FaCloudUploadAlt style={{ marginRight: &quot;8px&quot; }} /&gt;<br>                    Choose a File<br>                &lt;/FileLabel&gt;<br>                &lt;UploadButton onClick={onFileUpload}&gt;Upload&lt;/UploadButton&gt;<br><br>                {uploadPercentage &gt; 0 &amp;&amp; (<br>                    &lt;ProgressContainer&gt;<br>                        &lt;ProgressBar width={uploadPercentage} /&gt;<br>                        &lt;p&gt;{uploadPercentage}%&lt;/p&gt;<br>                    &lt;/ProgressContainer&gt;<br>                )}<br>            &lt;/Container&gt;<br>        &lt;/PageContainer&gt;<br>    );<br>};<br><br>export default FileUpload;</pre><p>After that, call this component in App.js, and you should see the result look like this. You need to run the following commands for both Node and React.</p><pre>node upload.js<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIm7LdZ_O5lruFxdObyLbg.png" /></figure><h3>Conclusion</h3><p>In this article, I aimed to teach you how to easily create a file upload module that allows larger files to be uploaded with a progress bar. If you enjoyed this article, please read it thoroughly and try implementing it yourself. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b553307cea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Event-Driven Systems with Google Pub/Sub and Node.js]]></title>
            <link>https://medium.com/@alamhamza873/building-scalable-event-driven-systems-with-google-pub-sub-and-node-js-9b0ed1b58656?source=rss-1f2a2d7d73b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b0ed1b58656</guid>
            <category><![CDATA[techcommunity]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[hamza alam]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 15:18:25 GMT</pubDate>
            <atom:updated>2024-09-24T15:18:25.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Recently, I’ve been working on a project where I need to send millions of notifications. Initially, I thought this would be a simple task, so I wrote basic synchronous code. It worked fine when traffic was normal, but as traffic increased, the limitations of this approach became apparent. The problem with synchronous programming is that one request must be completed before the next can begin, causing delays and slowing down the service during high traffic.</p><p>To handle this efficiently, the solution is to create a decoupled service that doesn’t rely on the speed of incoming requests. By doing this, we can build a scalable system capable of handling heavy loads without being overwhelmed by traffic.</p><p>Now, let’s dive into how to build this scalable system. We will use Google Pub/Sub, so let’s first understand what Google Pub/Sub is.</p><h3>What is Google PUB/SUB?</h3><p>Google Pub/Sub is a tool provided by Google Cloud (GCP). It works as an asynchronous and scalable messaging service that decouples services that produce messages. Pub/Sub enables you to create event-driven systems with components known as publishers and subscribers. Publishers can communicate with subscribers by broadcasting events rather than using synchronous remote procedure calls (RPCs).</p><h3>Setup Google Pub/Sub In Google Cloud</h3><p>First, you have to create a new account on Google Cloud</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvZkw93YNYYc_S7yH5n7jg.png" /><figcaption><strong>Google Cloud</strong></figcaption></figure><p>after creating an account search Google Pub/Sub Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ8Z7Lko2w7vGgTue5McNQ.png" /></figure><p>now you are on the Pub/Sub configuration page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TO4EGEzc_GCuTeECi3YrWA.png" /></figure><p>now you have to create a topic and subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzkS9jbbQivwhoKgPURN2A.png" /></figure><p>now you have to create a subscription on this page you have many options so you can explore all options but for this project, you have to select pull and create this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fi-FgtCxt9AgMrb_CkDCA.png" /></figure><p>now click on this Topic ID it will redirect to the page where you can add a message that will receive automatically to our code in node js where I will show you how we will send notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMJoXznx30aJMaiy73P9ow.png" /></figure><p>Now you can select the subscription and click on publish message so one more form will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdHvvyObR3NpgOzdcEWD2Q.png" /></figure><p>After publishing this, we will write a Node.js code that automatically receives the message. Additionally, when we write the Node.js code that subscribes to Pub/Sub, we will need a service key JSON file to connect to Pub/Sub. To get this, you’ll need to create a service account in Google Cloud. Simply search for “Service Account” in the GCP console, create a new service account, and after it’s created, click on the account and add a key. This will generate a service key JSON file for you.</p><h3>Implement Pub/Sub In Node JS</h3><p>first, you have to create a new directory called “pub-sub-demo”.</p><pre>mkdir pubsub-demo<br>cd pubsub-demo</pre><p>after creating a directory you have to initialize a project package.json file:</p><pre>npm init -y</pre><p>now you have to install <strong>Pub/Sub Node.js Client Library</strong>:</p><pre>npm install @google-cloud/pubsub</pre><p>now install a dotenv package to manage global variables.</p><pre>npm install dotenv</pre><p>then you have to set the service-key JSON file to authentication Pub/Sub</p><pre>GOOGLE_APPLICATION_CREDENTIALS=./service-key.json</pre><p>now create a node file name “Publisher.js”</p><pre>// Imports the Google Cloud client library<br>const { PubSub } = require(&#39;@google-cloud/pubsub&#39;);<br><br>// Instantiates a client<br>const pubSubClient = new PubSub();<br>require(&#39;dotenv&#39;).config();<br><br><br>// Publishes a message to a topic<br>async function publishMessage() {<br>  const topicName = &#39;&#39;; // Replace with your Pub/Sub topic<br>  const data = JSON.stringify({ message: &#39;Hello, Pub/Sub!&#39; });<br><br>  // Convert data to a Buffer<br>  const dataBuffer = Buffer.from(data);<br><br>  try {<br>    const messageId = await pubSubClient.topic(topicName).publishMessage({ data: dataBuffer });<br>    console.log(`Message ${messageId} published.`);<br>  } catch (error) {<br>    console.error(`Error publishing message: ${error.message}`);<br>  }<br>}<br><br>publishMessage();</pre><p>This code will publish your data to Pub/Sub. Additionally, you’ll need to create another file called “Subscriber” to handle receiving the messages.</p><pre>// Imports the Google Cloud client library<br>const { PubSub } = require(&#39;@google-cloud/pubsub&#39;);<br><br>// Instantiates a client<br>const pubSubClient = new PubSub();<br>require(&#39;dotenv&#39;).config();<br>// Function to listen for messages<br>async function listenForMessages() {<br>  const subscriptionName = &#39;&#39;; // Replace with your Pub/Sub subscription<br>  const timeout = 60; // Set the timeout for how long to listen for messages<br><br>  // References an existing subscription<br>  const subscription = pubSubClient.subscription(subscriptionName);<br><br>  // Event handler for incoming messages<br>  const messageHandler = (message) =&gt; {<br>    console.log(`Received message ${message.id}:`);<br>    console.log(`Data: ${message.data.toString()}`);<br>    console.log(`Attributes: ${JSON.stringify(message.attributes)}`);<br><br>    // Acknowledge the message<br>    message.ack();<br>  };<br><br>  // Listen for new messages<br>  subscription.on(&#39;message&#39;, messageHandler);<br><br>  // Timeout after X seconds<br>  setTimeout(() =&gt; {<br>    subscription.removeListener(&#39;message&#39;, messageHandler);<br>    console.log(`${timeout} seconds elapsed, stopping subscription listener.`);<br>  }, timeout * 1000);<br>}<br><br>listenForMessages();</pre><p>Now, when you run the publisher.js file, it will send a message to Pub/Sub, and then our subscriber.js file will automatically receive the message. Let me show you a video demonstration.</p><p><a href="https://streamable.com/hgjyvr">https://streamable.com/hgjyvr</a></p><h3>Conclusion</h3><p>The purpose of this article is to show that by using this type of architecture, where everything is decoupled, you can easily create a scalable system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b0ed1b58656" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>