<?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 The Backend Diaries on Medium]]></title>
        <description><![CDATA[Stories by The Backend Diaries on Medium]]></description>
        <link>https://medium.com/@imehboob?source=rss-e5c62f42f962------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VQjuiXFKbMCZrWPK-zirXQ.png</url>
            <title>Stories by The Backend Diaries on Medium</title>
            <link>https://medium.com/@imehboob?source=rss-e5c62f42f962------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imehboob/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[Backup, Restore, and Disaster Recovery in PostgreSQL: The Complete Guide | Part 6]]></title>
            <link>https://imehboob.medium.com/backup-restore-and-disaster-recovery-in-postgresql-the-complete-guide-part-6-045e5cbba27f?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/045e5cbba27f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 13:08:21 GMT</pubDate>
            <atom:updated>2026-07-09T13:08:21.314Z</atom:updated>
            <content:encoded><![CDATA[<p><em>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ma5dYxLq-Fm09y_uVmUOQw.png" /><figcaption>Image: OpenAI</figcaption></figure><h3>Table of Contents</h3><ul><li><strong>Quick Recap of Part 5</strong></li><li><strong>Who This Is For</strong></li><li><strong>What You Will Have Built by the End of Part 6</strong></li></ul><ol><li><strong>Why a Backup Nobody Has Restored Is Not a Backup</strong></li><li><strong>Understanding Backup Types in PostgreSQL</strong></li></ol><ul><li>A. Logical Backup</li><li>B. Physical Backup</li><li>C. Which One You Actually Need</li></ul><p><strong>3. Setting Up: A Fresh PostgreSQL Server With Real Data</strong></p><ul><li>A. One Assumption: Ubuntu</li><li>B. Install PostgreSQL and Rebuild the Ecommerce Schema</li><li>C. Seed It With Data</li></ul><p><strong>4. Method 1: SQL Dump Backup (pg_dump)</strong></p><ul><li>A. The WHY</li><li>B. Taking the Backup</li></ul><p><strong>5. Method 2: Custom Format Backup (pg_dump -Fc)</strong></p><ul><li>A. The WHY</li><li>B. Taking the Backup</li></ul><p><strong>6. Method 3: Full Physical Backup (pg_basebackup)</strong></p><ul><li>A. The WHY</li><li>B. What a WAL Actually Is</li><li>C. Taking the Backup</li></ul><p><strong>7. Restoring to a Different Machine</strong></p><ul><li>A. Preparing the Second Machine</li><li>B. Restoring the SQL Dump</li><li>C. Restoring the Custom Format Backup</li><li>D. Restoring the Full Physical Backup</li></ul><p><strong>8. Simulating a Real Disaster</strong></p><ul><li>A. Someone Drops the orders Table</li><li>B. Recovery With the SQL Dump</li><li>C. Recovery With the Custom Format Backup</li></ul><p><strong>9. Backup and Restore Gotchas</strong></p><p><strong>10. Beyond This Part: What Production Teams Actually Run</strong></p><p><strong>11. Conclusion</strong></p><p><strong>12. Resources</strong></p><p><strong>13. Next Part</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FjBrR6%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FjBrR6%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FjBrR6%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="1905" frameborder="0" scrolling="no"><a href="https://medium.com/media/41f03f5060b1099e8dfb5e36c5b7ead0/href">https://medium.com/media/41f03f5060b1099e8dfb5e36c5b7ead0/href</a></iframe><h3>Quick Recap of Part 5</h3><p><a href="https://medium.com/@imehboob/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c">In Part 5</a>, we took PostgreSQL off your local machine and put it on AWS, without touching the console once. We provisioned a full VPC from a Pulumi Python file: two subnets, a NAT Gateway, security groups, and two EC2 instances. The database server sat in a private subnet with no public IP. A pgAdmin server sat in a public subnet, talking to the database over the private network.</p><p>The point of <a href="https://medium.com/@imehboob/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c">Part 5</a> was that infrastructure you can review and repeat is worth more than infrastructure you remember clicking together three months ago.</p><p><strong>If you have not done </strong><a href="https://medium.com/@imehboob/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c"><strong>Part 5 yet</strong></a><strong>, start there first:</strong> <a href="https://imehboob.medium.com/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c"><strong>Part 5: PostgreSQL on AWS</strong></a></p><p>In this part, we stop building infrastructure and ask a harder question. If that server disappeared right now, do you actually have your data back, or do you just have a file you have never tested?</p><h3>Who This Is For</h3><p>This part is tagged <strong>[Intermediate]</strong>.</p><p>You need PostgreSQL installed somewhere with the ecommerce schema from Part 4 in it. That can be your local machine, the AWS setup from Part 5, or a brand new instance you spin up just for this part. It genuinely does not matter which. Backup and restore is a database-level skill, not an infrastructure-level one.</p><p><strong>Well, one assumption runs through this entire part: the commands here are Debian and Ubuntu centric</strong>, apt, systemd service names, file paths under /etc/postgresql and /var/lib/postgresql. If you are on a different distribution, the PostgreSQL commands stay identical. Only the package manager and a few paths change.</p><h3>What You Will Have Built by the End of Part 6</h3><p><strong>By the time you close this tab, you will have:</strong></p><ul><li>Taken a backup of a live PostgreSQL database using all three major methods: plain SQL dump, custom format dump, and full physical pg_basebackup</li><li>Understood exactly what each backup type contains, when engineers actually reach for it, and what it cannot do</li><li>Restored a backup onto a completely different machine that never had the data, the only real test of whether a backup works</li><li>Simulated an accidental DROP TABLE on a live system and recovered from it two different ways</li><li>A working list of the failure patterns that make backups look fine until the day you need them, and a sense of what tools take over once pg_dump and pg_basebackup stop being enough</li></ul><blockquote><em>okey, so let’s start.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*io6SnL_Wus7MuFijc9gCqw.gif" /><figcaption>postgresql backup/restore flow</figcaption></figure><h3>1. Why a Backup Nobody Has Restored Is Not a Backup</h3><p>So, in daily life, most engineers have a backup script somewhere. A cron job. Maybe a CI step. Something that runs pg_dump every night and drops a file in an S3 bucket.</p><blockquote>The fun fact is: Nobody checks it!</blockquote><p>The job runs green for eight months. Green means the command exited with status zero. But green does not always mean the file is restorable. Green does not mean the file has all your tables anyway! Green does not mean you remember which flags you used to create it, six months later, at 2 AM, with production down.</p><p>So, what’s the point?</p><blockquote><strong><em>A backup you have never restored is a theory.</em></strong></blockquote><blockquote><strong><em>It is not a backup.</em></strong></blockquote><p>The only way to know a backup actually works is to take it off the machine it came from and bring it back to life somewhere that has never seen your data. Not the same server. Not the same disk. A different machine, from scratch.</p><p>That is the real test, and it is the test most backup strategies never run until the day they are forced to.</p><p><strong>This part runs that test for all three backup methods PostgreSQL gives you.</strong></p><h3>2. Understanding Backup Types in PostgreSQL</h3><p>There are two completely different ways PostgreSQL can back up your data, and reaching for the right one depends less on which flags you know and more on what you are actually trying to survive.</p><h4>A. Logical Backup</h4><p><strong>When pg_dump runs, it does not look at your data files</strong>. It looks at your data, reads every row, and writes out the SQL needed to recreate all of it: CREATE TABLE statements, indexes, constraints, and the data itself as COPY commands or inserts. The result is a file that looks like a long SQL script, because that is exactly what it is.</p><p><strong>That approach has an interesting side effect</strong>. Since the output is just SQL, it does not care what PostgreSQL version produced it or what machine it runs on next. A dump from PostgreSQL 14 on an x86 server restores cleanly onto PostgreSQL 16 on an ARM machine. The dump only knows how to recreate objects and rows. Everything else about the original server, the version, the disk layout, the architecture, is completely irrelevant to it.</p><p><strong>This is why logical backups matter for migrations</strong>: moving between PostgreSQL versions, switching providers, or restoring a single table without touching the rest of the database. They also give you something you rarely think about until you need it, a backup you can open in a text editor and actually read. If you want to confirm your orders table definition is what you think it is, a plain SQL dump lets you do that. A physical backup does not.</p><p><strong>One detail worth knowing before the next section</strong>: a logical dump does not store your indexes. It stores the CREATE INDEX statement that built them. When you restore, PostgreSQL rebuilds every single index from scratch, row by row, in whatever order the restore reaches them. On 16,500 rows across five tables, you will not notice. On a table with 10 million rows and five indexes, that rebuild is where most of your restore time actually goes.</p><blockquote>pg_dump produces logical backups. Two output formats of it are covered as Methods 1 and 2 below.</blockquote><h4>B. Physical Backup</h4><p><strong>A physical backup skips the SQL description entirely.</strong> Instead of writing out what your data means, it copies the actual files PostgreSQL uses to store that data on disk, every table, every index already built, every configuration file, along with the transaction log records needed to bring those files to a consistent state.</p><p><strong>The reason this matters is speed</strong>. Generating INSERT statements for 10 million rows takes time and CPU. Restoring them means re-running every single one of those statements through the query planner, and rebuilding every index from nothing. On a large database, that can take hours.</p><p><strong>A physical backup skips all of that</strong>. It copies the files as they are, indexes included, already built. Restoring is closer to copying files back and starting a process than replaying a script. For a database of any real size, that difference is the gap between a 20-minute recovery and a 6-hour one.</p><p><strong>The tradeoff is that physical backups are tightly coupled to where they came from. </strong>You cannot take a pg_basebackup from PostgreSQL 14 and restore it onto PostgreSQL 16. The files speak a version-specific format.</p><p>When you need the whole cluster back exactly as it was, indexes, configuration, and all, as fast as physically possible, this is the tool you reach for. When you need portability across versions and architectures, it is not.</p><p>pg_basebackup produces physical backups. That is Method 3.</p><h4>C. Which One You Actually Need</h4><blockquote><em>Well, If you ask “</em><strong><em>should I use logical or physical</em></strong><em>,” you’re are usually asking the wrong question.</em></blockquote><blockquote><em>The real question is: </em><strong><em>what do I need to survive, and how fast do I need to be back?</em></strong></blockquote><p>A small side project database, a few hundred megabytes, changing PostgreSQL versions occasionally, need portability. Logical backup.</p><p>A production database backing an application people are actively using right now, where every minute of downtime costs money and trust, needs to come back as fast as physically possible. Physical backup.</p><p>However, mnost serious setups use both. Logical dumps for portability, migrations, and picking a single table out of the mess. Physical backups for the “<strong>the whole server is gone</strong>” scenario where speed is the only thing that matters.</p><blockquote><strong>In this blog part, we’ll explore both, properly, so you can make that call yourself instead of copying whatever the first Stack Overflow answer said.</strong></blockquote><h3>3. Setting Up: A Fresh PostgreSQL Server With Real Data</h3><h4>A. One Assumption: Ubuntu</h4><p>Everything from here assumes a fresh Ubuntu machine. It does not matter if that machine is a bare t2.micro on AWS with nothing else running on it, or your own laptop with a throwaway VM. What matters is that it is a clean install, and that you follow along with your own machine rather than reading past the commands.</p><p>If you already have the ecommerce schema running somewhere from Part 4 or Part 5, you can skip straight to Section 4 and back up that instance instead. The instructions below exist for anyone starting fresh for this part specifically.</p><h4>B. Install PostgreSQL and Rebuild the Ecommerce Schema</h4><p><strong>Install PostgreSQL:</strong></p><pre>sudo apt update<br>sudo apt install postgresql postgresql-contrib -y<br>sudo systemctl start postgresql<br>sudo systemctl enable postgresql</pre><p><strong>Set a password for the postgres user, exactly like we did in Part 5, before touching any auth config:</strong></p><pre>sudo -u postgres psql -c &quot;ALTER USER postgres PASSWORD &#39;postgres&#39;;&quot;</pre><p><strong>Update pg_hba.conf</strong></p><pre>sudo vim /etc/postgresql/*/main/pg_hba.conf</pre><p><strong>change the following line:</strong></p><pre># TYPE  DATABASE        USER            ADDRESS                 METHOD<br>local   all             postgres                                peer</pre><p><strong>to:</strong></p><pre># TYPE  DATABASE        USER            ADDRESS                 METHOD<br>local   all             postgres                                scram-sha-256</pre><p><strong>Restart the PostgreSQL service:</strong></p><pre>sudo systemctl restart postgresql</pre><p><strong>Create the database and connect to it:</strong></p><pre>sudo -u postgres psql -c &quot;CREATE DATABASE ecommerce;&quot;<br>sudo -u postgres psql -d ecommerce</pre><p><strong>Create the below five tables:</strong></p><pre>-- user table <br>CREATE TABLE users (<br>    user_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    email VARCHAR(150) NOT NULL UNIQUE,<br>    phone VARCHAR(20),<br>    address TEXT,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);<br><br>-- products table<br>CREATE TABLE products (<br>    product_id SERIAL PRIMARY KEY,<br>    name VARCHAR(200) NOT NULL,<br>    description TEXT,<br>    price DECIMAL(10,2) NOT NULL,<br>    stock_quantity INT NOT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);<br><br>-- orders table<br>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    user_id INT NOT NULL REFERENCES users(user_id),<br>    total_amount DECIMAL(10,2) NOT NULL,<br>    status VARCHAR(50) NOT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);<br><br>-- order items table<br>CREATE TABLE order_items (<br>    order_item_id SERIAL PRIMARY KEY,<br>    order_id INT NOT NULL REFERENCES orders(order_id),<br>    product_id INT NOT NULL REFERENCES products(product_id),<br>    quantity INT NOT NULL,<br>    price DECIMAL(10,2) NOT NULL<br>);<br><br>-- payments table<br>CREATE TABLE payments (<br>    payment_id SERIAL PRIMARY KEY,<br>    order_id INT NOT NULL REFERENCES orders(order_id),<br>    payment_method VARCHAR(50) NOT NULL,<br>    payment_status VARCHAR(50) NOT NULL,<br>    transaction_id VARCHAR(100) NOT NULL UNIQUE,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);<br></pre><p><strong>Exit psql:</strong></p><pre>\q</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*yri3PjJXe5nKKoFAd6JVEQ.png" /><figcaption>teh 5 tables</figcaption></figure><p>If any of this feels unfamiliar, that is exactly <a href="https://medium.com/@imehboob/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917">what Part 4 covers in full</a>, including why each of these five tables exists as a separate table instead of being collapsed together.</p><h4>C. Seed It With Data</h4><p>Using the same seeding pattern from <a href="https://medium.com/@imehboob/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917">Part 4</a>: a Python script with Faker, generating 1000 users, 500 products, 5000 orders, 10,000 order items, and 5000 payments.</p><p><strong>Install the dependencies:</strong></p><pre>sudo apt install python3-venv python3-pip libpq-dev python3-dev -y<br><br>mkdir -p pg-backup-restore &amp;&amp; cd pg-backup-restore<br><br>python3 -m venv ecommerce-env<br><br>source ecommerce-env/bin/activate<br><br>pip install psycopg2-binary faker</pre><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote>Use<em> </em><em>psycopg2-binary</em>, not<em> </em><em>psycopg2</em>. The binary package ships precompiled and installs cleanly on a fresh Ubuntu machine.</blockquote><blockquote>Building<em> </em><em>psycopg2 </em>from source needs a C compiler and PostgreSQL development headers you likely do not have on a clean install yet.</blockquote><p><strong>Run the exact seeding script below</strong></p><pre>import psycopg2<br>from faker import Faker<br>import random<br>from datetime import datetime, timedelta<br><br>fake = Faker()<br><br># database connection parameters<br>conn = psycopg2.connect(<br>    dbname=&quot;ecommerce&quot;, # change the database name to your own database name<br>    user=&quot;postgres&quot;,<br>    password=&quot;postgres&quot;, # change the password to your own password<br>    host=&quot;localhost&quot;,<br>    port=&quot;5432&quot;<br>)<br>cursor = conn.cursor()<br><br># function to generate and insert users<br>def generate_users(num_users):<br>    used_emails = set()  <br>    for _ in range(num_users):<br>        while True: <br>            name = fake.name()<br>            email = fake.email()<br>            if email not in used_emails:  # email is unique<br>                used_emails.add(email)<br>                break<br>        phone = fake.phone_number()[:20]  <br>        address = fake.address()<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO users (name, email, phone, address, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (name, email, phone, address, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_users} users.&quot;)<br><br># function to generate and insert products<br>def generate_products(num_products):<br>    for _ in range(num_products):<br>        name = fake.word().capitalize() + &quot; &quot; + fake.word().capitalize()<br>        description = fake.sentence()<br>        price = round(random.uniform(10, 1000), 2)<br>        stock_quantity = random.randint(10, 1000)<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO products (name, description, price, stock_quantity, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (name, description, price, stock_quantity, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_products} products.&quot;)<br><br># function to generate and insert orders<br>def generate_orders(num_orders):<br>    cursor.execute(&quot;SELECT user_id FROM users&quot;)<br>    user_ids = [row[0] for row in cursor.fetchall()]<br>    for _ in range(num_orders):<br>        user_id = random.choice(user_ids)<br>        total_amount = round(random.uniform(10, 1000), 2)<br>        status = random.choice([&#39;pending&#39;, &#39;completed&#39;, &#39;cancelled&#39;])<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO orders (user_id, total_amount, status, created_at) VALUES (%s, %s, %s, %s)&quot;,<br>            (user_id, total_amount, status, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_orders} orders.&quot;)<br><br># function to generate and insert order_items<br>def generate_order_items(num_items):<br>    cursor.execute(&quot;SELECT order_id FROM orders&quot;) # get the order_id from orders table<br>    order_ids = [row[0] for row in cursor.fetchall()]<br>    cursor.execute(&quot;SELECT product_id, price FROM products&quot;) # get the product_id, price from products table<br>    products = cursor.fetchall()<br>    for _ in range(num_items):<br>        order_id = random.choice(order_ids)<br>        product_id, price = random.choice(products)<br>        quantity = random.randint(1, 10)<br>        cursor.execute(<br>            &quot;INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (%s, %s, %s, %s)&quot;,<br>            (order_id, product_id, quantity, price)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_items} order items.&quot;)<br><br># function to generate and insert payments<br>def generate_payments(num_payments):<br>    cursor.execute(&quot;SELECT order_id FROM orders&quot;)<br>    order_ids = [row[0] for row in cursor.fetchall()]<br>    for _ in range(num_payments):<br>        order_id = random.choice(order_ids)<br>        payment_method = random.choice([&#39;credit_card&#39;, &#39;paypal&#39;, &#39;bank_transfer&#39;])<br>        payment_status = random.choice([&#39;success&#39;, &#39;pending&#39;, &#39;failed&#39;])<br>        transaction_id = fake.uuid4()<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO payments (order_id, payment_method, payment_status, transaction_id, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (order_id, payment_method, payment_status, transaction_id, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_payments} payments.&quot;)<br><br># generate data<br>generate_users(1000)          # insert 1000 users<br>generate_products(500)        # ionsert 500 products<br>generate_orders(5000)         # isert 5000 orders<br>generate_order_items(10000)   # insert 10000 order items<br>generate_payments(5000)       # insert 5000 payments<br><br># close the connection<br>cursor.close()<br>conn.close()</pre><p><strong>Once it finishes, verify the row counts:</strong></p><pre>sudo -u postgres psql -d ecommerce -c &quot;<br>SELECT &#39;users&#39; AS table_name, COUNT(*) FROM users<br>UNION ALL SELECT &#39;products&#39;, COUNT(*) FROM products<br>UNION ALL SELECT &#39;orders&#39;, COUNT(*) FROM orders<br>UNION ALL SELECT &#39;order_items&#39;, COUNT(*) FROM order_items<br>UNION ALL SELECT &#39;payments&#39;, COUNT(*) FROM payments;<br>&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*gy-QxyreqUICWO4U2wi4Fw.png" /><figcaption>data seeded in postgres</figcaption></figure><p><strong>21,500 rows. Now there is something real to lose, and something real to get back.</strong></p><h3>4. Method 1: SQL Dump Backup (pg_dump)</h3><h4>A. The WHY</h4><p><strong>Let’s assume your team is migrating off PostgreSQL 14 onto PostgreSQL 16 next quarter</strong>. Or you are moving this database from an old provider to a new one, and the new one does not support the same PostgreSQL version. Or you maybe just want a backup you can open in a text editor and actually read, to confirm your orders table definition is what you think it is.</p><p><strong>None of those situations care about disk-level speed</strong>. They need a backup that survives a version change and a platform change without caring what either of those things are. That is exactly what pg_dump gives you.</p><p><strong>pg_dump writes out every object in your database as plain SQL</strong>, CREATE TABLE, CREATE INDEX, INSERT, in a single script. Run that script against any PostgreSQL instance, old or new, same machine or a different continent, and you get your database back.</p><p><strong>It runs against a live database without locking readers or writers out.</strong> PostgreSQL takes a consistent snapshot at the moment pg_dump starts, so the backup reflects the database as it looked at that instant, even if rows change while the dump is still running.</p><h4>B. Taking the Backup</h4><p><strong>Run pg_dump against the ecommerce database:</strong></p><pre>pg_dump -U postgres -h localhost -d ecommerce -f ecommerce_backup.sql</pre><p><strong>What each flag does:</strong></p><ul><li>-U postgres connects as the postgres user</li><li>-h localhost connects over TCP instead of the local Unix socket, which forces password auth so you can see the real connection flow</li><li>-d ecommerce is the database being dumped</li><li>-f ecommerce_backup.sql writes the output to a file instead of stdout</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*wDgAkISi-0fFjgxawx8hyw.png" /><figcaption>logical simple backup with pg_dump</figcaption></figure><p><strong>Open the file and look at the first 30 lines:</strong></p><pre>head -n 30 ecommerce_backup.sql</pre><p>You will see SET statements configuring the session, followed by CREATE TABLE statements matching exactly what you wrote in Section 3B. Scroll further and you hit thousands of COPY and INSERT-style data lines.</p><blockquote><em>This file is not a black box.</em></blockquote><blockquote><em>It is a script. You can read every line of it, understand exactly what it will do before you run it, and even hand-edit a single line if you needed to.</em></blockquote><blockquote><strong><em>That readability is the entire value of a plain SQL dump.</em></strong></blockquote><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote>A pg_dump doubles as a free, low-effort corruption check. It reads through every row in every table sequentially to write the dump.</blockquote><blockquote>If a data page is corrupted, pg_dump will fail with an error instead of silently producing a file.</blockquote><blockquote>It is not a replacement for a real integrity check, PostgreSQL&#39;s<em> </em><em>amcheck </em>module does that properly, including for indexes.</blockquote><blockquote>But if your nightly<em> </em><em>pg_dump </em>job has been failing quietly and nobody noticed, that failure was telling you something more urgent than &quot;<strong>the backup didn&#39;t run.</strong>&quot;</blockquote><p><strong>You can also dump one table instead of the whole database</strong>, useful when you want a quick safety copy before doing something risky to a single table:</p><pre>pg_dump -U postgres -h localhost -d ecommerce -t orders -f orders_only.sql</pre><p>And if you manage more than one database on the same server and want everything, schemas, roles, and all databases, in one file, pg_dumpall is the tool for that, not pg_dump:</p><pre>pg_dumpall -U postgres -h localhost -f full_cluster.sql</pre><p>pg_dumpall only outputs plain SQL, never the custom format from Method 2. Reach for it when you need the whole server&#39;s worth of roles and databases in one place, not when you need one database backed up well.</p><h3>5. Method 2: Custom Format Backup (pg_dump -Fc)</h3><h4>A. The WHY</h4><p>The plain SQL dump you just took works. But once your database grows past toy size, it runs into two problems that are hard to ignore.</p><p><strong>First, it is not compressed</strong>. A 500MB database produces a 500MB or larger dump file. At real scale, that adds up in storage cost and transfer time.</p><p><strong>The second problem is more important than the first</strong>. Restoring a SQL dump is all or nothing. If you only need the orders table back and the rest of the database is fine, you still have to either hand-edit a multi-thousand-line SQL file, or replay the whole script and then delete everything you did not need. Neither option is something you want to be doing at 2 AM with production down.</p><p><strong>The custom format solves both</strong>. pg_dump -Fc writes a compressed, PostgreSQL-specific archive instead of plain SQL. It is not human-readable anymore, but it comes with something the plain dump does not:</p><p><strong>pg_restore can read the archive’s table of contents and pull out exactly the objects you ask for</strong>, nothing else. One table. Three tables. Everything except that one table you do not want. The choice is yours at restore time, not at backup time.</p><p><strong>When you reach for it:</strong> any database beyond toy size, and any situation where “<strong>restore just this one table</strong>” is a realistic need, which in practice is most production situations.</p><h4>B. Taking the Backup</h4><p><strong>Run pg_dump with the custom format flag:</strong></p><pre>pg_dump -U postgres -h localhost -d ecommerce -Fc -f ecommerce_backup.dump</pre><p>-Fc is the only difference from Method 1. Everything else about how the command runs against the live database, consistent snapshot, no locking readers or writers, stays identical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvjxtxQc2o817Wi11ATVZA.png" /><figcaption>see the storage differences between the .dump and .sql file</figcaption></figure><p><strong>Try opening it as text:</strong></p><pre>head -c 100 ecommerce_backup.dump</pre><p>Here, you get binary noise, not SQL. That is expected. This file speaks pg_restore&#39;s language, not psql&#39;s.</p><blockquote><em>The plain dump is a script you can read.</em></blockquote><blockquote><em>The custom format dump is an archive you can query.</em></blockquote><blockquote><strong><em>You will feel the difference the first time you need one table back out of a hundred.</em></strong></blockquote><h3>6. Method 3: Full Physical Backup (pg_basebackup)</h3><h4>A. The WHY</h4><p><strong>Both methods above are logical</strong>. They describe your data. Neither of them touches PostgreSQL’s actual data files, and neither of them is fast on a large database, because restoring means replaying statements and rebuilding every index from raw rows, exactly as explained in Section 2B.</p><p><strong>pg_basebackup takes a completely different approach</strong>. It copies PostgreSQL’s real data directory: the raw files that back every table, every index already built, every setting, straight off a running server. Restoring is close to copying those files back and starting PostgreSQL up again. <strong>No replay. No index rebuild from scratch</strong>.</p><blockquote><strong>the tradeoff is portability</strong>. A physical backup is tied to the PostgreSQL major version and, in most cases, the OS architecture it came from.</blockquote><blockquote><strong>You cannot take a </strong><strong>pg_basebackup from PostgreSQL 14 and restore it onto PostgreSQL 16</strong>.</blockquote><blockquote><strong><em>Logical backups do not have that restriction</em>. Physical backups trade portability for speed.</strong></blockquote><p><strong>When you need it:</strong> the entire server is gone and downtime is expensive, you are setting up a replica for high availability, or you need every setting, every index, and every byte back exactly as it was, as fast as physically possible.</p><h4>B. What a WAL Actually Is</h4><p><strong>Before running the command, one term needs a plain explanation: WAL, Write-Ahead Log.</strong></p><p>Every change PostgreSQL makes to your data, before it touches the actual table files, gets written to the WAL first. You can assume of it as a running diary of every modification, in order, with a timestamp, BEFORE the data is written in physical data block.</p><blockquote>Assume the WAL like a bank’s transaction ledger.</blockquote><blockquote>The bank does not update your balance the moment you swipe your card. It writes the transaction to the ledger first. If the system crashes mid-update, the ledger tells the bank exactly what was in progress and how to finish it correctly.</blockquote><blockquote>PostgreSQL does the same thing. Data files get updated. The WAL records what happened, in order, so that if the process dies mid-write, PostgreSQL can replay the WAL on startup and land in a consistent state.</blockquote><p>A physical backup by itself is a snapshot of files that were being written to while you copied them. It is not automatically consistent on its own. It needs the WAL records generated during the copy to become consistent. That is exactly what the flags in the next command handle.</p><h4>C. Taking the Backup</h4><p><strong>Create a directory to hold the backup:</strong></p><pre>sudo mkdir -p /var/backups/postgres_physical<br>sudo chown postgres:postgres /var/backups/postgres_physical</pre><p><strong>Run pg_basebackup as the postgres user:</strong></p><pre>sudo -u postgres pg_basebackup -D /var/backups/postgres_physical -Fp -Xs -P -R</pre><p><strong>What each flag does:</strong></p><ul><li>-D /var/backups/postgres_physical is the output directory</li><li>-Fp writes plain files instead of a tarball, easier to inspect</li><li>-Xs streams the WAL records generated during the backup alongside it, so the backup is self-consistent the moment it finishes</li><li>-P shows progress while it runs</li><li>-R writes the connection settings needed to turn this into a replica later, <strong>useful groundwork for the replication parts later in this series</strong></li></ul><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote>This ran as the<em> </em><em>postgres </em>superuser, so it has every privilege it needs by default.</blockquote><blockquote>If you ever set up a dedicated, lower-privilege user just for taking backups, that user needs the<em> </em><em>REPLICATION </em>role attribute, or it needs to be granted the<em> </em><em>pg_read_all_data </em>and replication-related roles PostgreSQL provides.</blockquote><blockquote>pg_basebackup talks to the server using the replication protocol, not a normal SQL connection, <strong>and a regular read-only user cannot use it without that grant.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOwmr4F8ObYZLfm3hesYfA.png" /><figcaption>physical backup</figcaption></figure><p><strong>Look at what got copied:</strong></p><pre>sudo -u postgres ls /var/backups/postgres_physical</pre><p>You will see base, pg_wal, postgresql.conf, pg_hba.conf, everything PostgreSQL needs to start up as a complete, independent instance. Not a script describing your data. <strong>The actual data.</strong></p><h3>7. Restoring to a Different Machine</h3><p>This is the part that actually proves any of the last three sections were worth doing. Everything so far produced a file or a directory sitting on the same server the data came from. That proves nothing. A backup that only works on the machine that made it is not a backup. It is a snapshot with extra steps.</p><blockquote>Well, you can also just use same VM, or same local machine, if that you’re using; if getting another VM not feasible for you. Just tellin, in this case, you must either drop the previous database, or restore the backups with new database name.</blockquote><h4>A. Preparing the Second Machine</h4><p>Spin up a second Ubuntu machine. It genuinely does not matter whether this is a second EC2 instance, a fresh VM on your laptop, or a second cloud provider entirely. The only requirement is that it has never seen the ecommerce database, and that it can reach the first machine, or that you can copy files between them.</p><p><strong>Install PostgreSQL on the second machine, same as before:</strong></p><pre>sudo apt update<br>sudo apt install postgresql postgresql-contrib -y<br>sudo systemctl start postgresql<br>sudo systemctl enable postgresql<br>sudo -u postgres psql -c &quot;ALTER USER postgres PASSWORD &#39;postgres&#39;;&quot;</pre><p><strong>Copy the backup files from the first machine to the second:</strong></p><pre>scp ecommerce_backup.sql username@second-machine-ip:~/<br>scp ecommerce_backup.dump username@second-machine-ip:~/<br>sudo tar czf physical_backup.tar.gz -C /var/backups postgres_physical<br>scp physical_backup.tar.gz username@second-machine-ip:~/</pre><p>Three files, one for each method, all sitting on a machine that has genuinely never had this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*7Yj60kTLtgJlpVSqGBKmOg.png" /><figcaption>the second vm got the backup files</figcaption></figure><h4>B. Restoring the SQL Dump</h4><p><strong>Create a fresh, empty database on the second machine:</strong></p><pre>sudo -u postgres psql -c &quot;CREATE DATABASE ecommerce;&quot;</pre><p><strong>Restore the plain SQL dump:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -f ecommerce_backup.sql</pre><p>This replays every CREATE TABLE and every insert line in order, and rebuilds every index from scratch as it goes. On 21,500 rows across five tables, expect this to take a noticeable handful of seconds, not instant.</p><p><strong>Verify:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -c &quot;SELECT COUNT(*) FROM orders;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*kSeovhiTJTobeyDd23Qwyg.png" /><figcaption>the logical data restore</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*CbrnQUqZmMW_D3A7pmuLIg.png" /><figcaption>verify logical data restore successfully</figcaption></figure><p><strong>5000. Same number as the source machine. This machine had nothing an hour ago.</strong></p><h4>C. Restoring the Custom Format Backup</h4><p><strong>Create a second fresh database to restore into:</strong></p><pre>sudo -u postgres psql -c &quot;CREATE DATABASE ecommerce_custom;&quot;</pre><p><strong>Restore the full archive:</strong></p><pre>pg_restore -U postgres -h localhost -d ecommerce_custom ecommerce_backup.dump</pre><p>pg_restore reads the archive&#39;s internal table of contents and issues the correct commands in the correct dependency order automatically. You do not need to worry about users being created before orders references it. The archive already knows.</p><p><strong>On a bigger database than this one, restoring is the point where the custom format pulls ahead again.</strong> Add -j to restore multiple tables in parallel across CPU cores instead of one at a time:</p><pre>pg_restore -U postgres -h localhost -d ecommerce_custom -j 4 ecommerce_backup.dump</pre><p>-j 4 uses four parallel workers. This only works with the custom format, never with plain SQL dumps, since psql replays a script top to bottom with no concept of parallel workers.</p><p><strong>Now the part that makes this format worth the extra step. Restore only one table:</strong></p><pre># create a new database<br>sudo -u postgres psql -c &quot;CREATE DATABASE ecommerce_selective;&quot;<br><br># restore a selective table <br>pg_restore -U postgres -h localhost -d ecommerce_selective -t products ecommerce_backup.dump</pre><p><strong>Verify only products came across:</strong></p><pre>psql -U postgres -h localhost -d ecommerce_selective -c &quot;\dt&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq3CMlpql472A95jvCoaKw.png" /><figcaption>the full custom format restore as well as selective table restore</figcaption></figure><blockquote>The plain SQL dump gives you all or nothing.</blockquote><blockquote><em>The custom format archive gives you exactly the table you asked for, and nothing else, on a database that never saw the rest of the schema.</em></blockquote><blockquote><strong><em>This is the restore flexibility Section 5 promised. Here it is, actually working.</em></strong></blockquote><h4>D. Restoring the Full Physical Backup</h4><p>This one is structurally different from the other two. You are not restoring into an existing PostgreSQL instance. You are replacing PostgreSQL’s entire data directory with the copy you took, and starting a fresh PostgreSQL process against it.</p><p><strong>Stop PostgreSQL on the second machine:</strong></p><pre>sudo systemctl stop postgresql</pre><p><strong>Detect the installed PostgreSQL version instead of hardcoding it.</strong> Ubuntu’s apt repository installs whatever the current default major version is, and that number changes as Ubuntu releases change. Capture it into a variable once, then reuse it for every path below:</p><pre>PG_VERSION=$(ls /etc/postgresql)<br>echo &quot;Detected PostgreSQL version: $PG_VERSION&quot;</pre><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote>A bare wildcard like<em> </em><em>/var/lib/postgresql/*/main </em>works fine for a command like editing<em> </em><em>pg_hba.conf</em>, where the directory already exists and the glob only has to match something that is there.</blockquote><blockquote><strong>It is riskier for the next few steps</strong><em>*:</em></blockquote><blockquote><em>where the same directory gets deleted and recreated. If the glob does not match anything at the moment a command runs, the shell passes the literal, unexpanded string through instead of failing, and a* </em><em>cp </em>or<em> </em><em>rm </em>can silently do unexpected thing.</blockquote><blockquote>Capturing the version into a variable once avoids that entirely, and it is still zero hardcoding: run this same command on PostgreSQL 14, 16, or 18, and it detects whichever one is actually installed.</blockquote><p><strong>Remove the existing data directory using the detected version:</strong></p><pre>sudo rm -rf /var/lib/postgresql/$PG_VERSION/main</pre><p><strong>Extract the physical backup you copied over into that exact location:</strong></p><pre>mkdir ~/physical_restore<br>tar xzf physical_backup.tar.gz -C ~/physical_restore<br>sudo cp -r ~/physical_restore/postgres_physical /var/lib/postgresql/$PG_VERSION/main</pre><p><strong>Fix ownership and permissions. PostgreSQL refuses to start if these are wrong:</strong></p><pre>sudo chown -R postgres:postgres /var/lib/postgresql/$PG_VERSION/main<br>sudo chmod -R 700 /var/lib/postgresql/$PG_VERSION/main</pre><p><strong>Start PostgreSQL:</strong></p><pre>sudo systemctl start postgresql</pre><p><strong>Check the logs if it does not come up cleanly:</strong></p><pre>sudo journalctl -u postgresql -n 50</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*030fYH0OSJ_VPVWoui_qug.png" /><figcaption>the physical backup completed with proper file permission</figcaption></figure><p><strong>Verify:</strong></p><pre>sudo -u postgres psql -d ecommerce -c &quot;SELECT COUNT(*) FROM order_items;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Ficuy__yEKwaIm_QHXRglA.png" /><figcaption>the new physical restore has the correct data after restore</figcaption></figure><blockquote><em>This machine did not run a single </em><em>INSERT.</em></blockquote><blockquote><em>It did not create a single table.</em></blockquote><blockquote><strong><em>It copied files and started a process, and the entire database, indexes included, was already there.</em></strong></blockquote><p>That is the speed physical backup buys you, and it is also exactly why it demands more care during restore. One wrong permission, one wrong PostgreSQL version between the two machines, and it refuses to start.</p><h3>8. Simulating a Real Disaster</h3><p>Well! backups exist for one moment. The moment someone runs a command they should not have.</p><h4>A. Someone Drops the orders Table</h4><p>now, go back to the first machine, the one with your original, live ecommerce database.</p><p><strong>Run this. It is meant to hurt!:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -c &quot;DROP TABLE orders CASCADE;&quot;</pre><p>CASCADE also drops anything that depends on orders, which includes the foreign keys in order_items and payments. This is not a contained mistake.</p><p><strong>Confirm the damage:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -c &quot;\dt&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqMY1e2G0ZtiM_mf9d5rqA.png" /><figcaption>order table dropped</figcaption></figure><blockquote><strong>orders is gone. Every order_items row that referenced it is now orphaned. Every payment tied to a dropped order is floating with no parent. This is what a production incident actually looks like.</strong></blockquote><h4>B. Recovery With the SQL Dump</h4><p>The plain SQL dump you took in Method 1 is a full script. Restoring it means replaying the whole thing.</p><p><strong>Restore the entire database from the SQL dump:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -f ecommerce_backup.sql</pre><p>This works. orders comes back, with every row it had at backup time. But so does everything else, re-created from scratch, even the tables that were never touched by the DROP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dedHcwsaYVC3kQS0dQdMQ.png" /><figcaption>recovery with normal logical restore</figcaption></figure><blockquote><strong><em>This restores everything you asked for and everything you did not.</em></strong></blockquote><blockquote><em>On a small database, that cost is nothing. On a large one, replaying a full dump just to fix one table is minutes or hours you did not need to spend.</em></blockquote><h4>C. Recovery With the Custom Format Backup</h4><p><strong>Drop orders again to reset the scenario:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -c &quot;DROP TABLE orders CASCADE;&quot;</pre><p><strong>This time, pull back only the orders table from the custom format archive:</strong></p><pre>pg_restore -U postgres -h localhost -d ecommerce -t orders ecommerce_backup.dump</pre><p><strong>Verify:</strong></p><pre>psql -U postgres -h localhost -d ecommerce -c &quot;SELECT COUNT(*) FROM orders;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_bQKkDmhSQF-Zht2-y4cw.png" /><figcaption>restored the only order table with pg_restore file</figcaption></figure><blockquote><em>-t orders told </em><em>pg_restore to touch exactly one table.</em></blockquote><blockquote><em>Nothing else in the database was replayed, dropped, or recreated.</em></blockquote><blockquote><strong><em>This is the entire reason Method 2 exists. The moment you feel the difference between these two recoveries is the moment the custom format stops being an abstract flag and starts being the format you reach for by default.</em></strong></blockquote><p>order_items and payments will still show broken foreign key references from the CASCADE, since those rows referenced orders that got dropped and never came back with new IDs matching the old ones.</p><blockquote>In a real incident, this is exactly why teams restore into a separate scratch database first, compare, and then carefully patch the live one instead of overwriting it blind. That comparison step is worth its own part later in this series.</blockquote><h3>9. Backup and Restore Gotchas</h3><p>So, six things that look fine until they cost you a restore at the worst possible time.</p><p><strong>A password set after </strong><strong>pg_hba.conf changes locks you out, not in.</strong> If you change authentication to require a password before setting one, you cannot log in to set it either. Password first, always, exactly like Part 5 covered for remote access.</p><p><strong>A pg_dump taken while a long transaction is open will wait, not lie.</strong> pg_dump needs a consistent snapshot. If something is holding a long-running transaction open on a table you are dumping, pg_dump can stall waiting for a lock rather than silently producing a corrupt file. A stuck backup job is usually this, not a broken pg_dump. Worth knowing too: since PostgreSQL uses MVCC to manage concurrency, a very long-running dump on a busy database can add real read overhead in the background while it is in progress, not just take a long time itself.</p><p><strong>A physical backup restored onto a different major PostgreSQL version will not start.</strong> pg_basebackup is tied to the exact major version that produced it. Compare $PG_VERSION on both machines before you trust a physical restore. A mismatched version here fails loudly, but only after you have already spent the time on the restore.</p><p><strong>CASCADE on a </strong><strong>DROP TABLE takes dependents down with it, silently, unless you read the output.</strong> The disaster simulation in Section 8 used CASCADE on purpose. In a real incident, someone often adds CASCADE without knowing what depends on the table they are dropping. PostgreSQL tells you what it dropped in the output. Read it before you assume the blast radius was one table.</p><p><strong>A backup and a replica are not the same safety net.</strong> A replica is a live, continuously updated copy of your database that can take over traffic in seconds. A backup is a point-in-time snapshot that takes minutes to hours to bring back. Replicas protect you from downtime. Backups protect you from someone dropping a table, corrupting data, or a replica that faithfully copied the mistake to itself a second later. You want both, and neither one substitutes for the other.</p><p><strong>A backup stored next to the database it backs up is not a backup, it is a second copy of the same risk.</strong> If the disk, the server, or the account holding both gets destroyed or compromised, you lose both at once. This is where the old 3–2–1 rule earns its keep: three copies of your data, on two different kinds of storage, with at least one copy somewhere physically or logically separate from the source.</p><h3>10. Beyond This Part: What Production Teams Actually Run</h3><p>We’re focusing on the tools that come with PostgreSQL because it’s essential to understand how they work. To really get a production backup tool, you need to know what’s happening behind the scenes with pg_dump and pg_basebackup. These are the foundation, and without a solid grasp of them, it’s tough to make sense of more advanced tools.</p><p>But it is worth naming what comes next. pg_basebackup has no concept of an incremental backup. Every run copies the entire cluster from zero, which gets expensive fast on a large, frequently changing database. Production setups typically layer a purpose-built tool on top of it, most commonly pgBackRest, sometimes WAL-G.</p><p>Both add full, differential, and incremental backups, parallel workers to speed up the copy itself, checksum validation so a corrupted backup gets caught before you rely on it, and proper point-in-time recovery, restoring to the exact second before someone ran a bad migration, not just to the last nightly backup.</p><p>That is also where continuous WAL archiving lives: keeping a running stream of every WAL segment PostgreSQL generates, so a base backup plus the archived WAL between it and the moment of failure can rebuild the database to almost any second you choose.</p><p>It is a genuinely deep topic on its own, and one this series will come back to properly once replication is on the table in later parts, since PITR and streaming replication share the same WAL mechanics you just learned the intuition for in Section 6B.</p><p>For now, what matters is this: you understand what a backup actually contains, why one type is fast and another is portable, and what it takes to prove either of them works. Everything pgBackRest or WAL-G automate, you now understand well enough to sanity check.</p><h3>11. Conclusion</h3><p>You took the same 21,500 rows and backed them up three different ways, then proved every single one of those backups actually worked by bringing them back to life on a machine that had never seen this data before.</p><p>The SQL dump gave you something portable and readable. The custom format gave you the same data with compression and the ability to pull back exactly one table instead of the whole database. The physical backup gave you speed, at the cost of being tied to the exact version and machine class it came from.</p><blockquote><em>A backup script that has never been restored is not a safety net.</em></blockquote><blockquote><strong><em>It is a guess about a safety net.</em></strong></blockquote><p>The only way to know which of these three you actually need is to have run all three, seen what each one costs you and what each one saves you, and felt the difference between restoring one table and replaying an entire database. Now you have.</p><p>Part 7 goes one level deeper into PostgreSQL itself. We stop protecting the data from the outside and start looking at how PostgreSQL protects it on the inside, starting with B-Tree indexes and exactly what happens the moment you run CREATE INDEX.</p><h3>12. Resources</h3><ul><li><strong>PostgreSQL pg_dump Documentation:</strong> Complete reference for every pg_dump flag and output format. <a href="https://www.postgresql.org/docs/current/app-pgdump.html">postgresql.org/docs/current/app-pgdump.html</a></li><li><strong>PostgreSQL pg_restore Documentation:</strong> Full guide to selective and full restores from custom format archives. <a href="https://www.postgresql.org/docs/current/app-pgrestore.html">postgresql.org/docs/current/app-pgrestore.html</a></li><li><strong>PostgreSQL pg_basebackup Documentation:</strong> Physical backup reference, including WAL streaming options. <a href="https://www.postgresql.org/docs/current/app-pgbasebackup.html">postgresql.org/docs/current/app-pgbasebackup.html</a></li><li><strong>PostgreSQL WAL Internals:</strong> How the write-ahead log actually works under the hood. <a href="https://www.postgresql.org/docs/current/wal-intro.html">postgresql.org/docs/current/wal-intro.html</a></li><li><strong>PostgreSQL amcheck Module:</strong> A proper corruption check for tables and indexes, deeper than what pg_dump catches incidentally. <a href="https://www.postgresql.org/docs/current/amcheck.html">postgresql.org/docs/current/amcheck.html</a></li><li><strong>pgBackRest:</strong> The production-grade physical backup tool referenced in Section 10. <a href="https://pgbackrest.org/">pgbackrest.org</a></li><li><strong>Part 5 of this series:</strong> Provisioning PostgreSQL on AWS with Pulumi, no console clicks. <a href="https://imehboob.medium.com/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c">Part 5</a></li><li><strong>Part 4 of this series:</strong> The ecommerce schema and the seeding script used throughout this part. <a href="https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917">Part 4</a></li><li><strong>Backup and Restore blog Tiger Data: </strong><a href="https://www.tigerdata.com/blog/database-backups-and-disaster-recovery-in-postgresql-your-questions-answered">Different view</a> on the same concept.</li><li><strong>Another good resource: </strong>on backup and restore on <a href="https://medium.com/@pawale7663/postgresql-backup-and-restore-complete-guide-to-backing-up-and-restoring-databases-14d19bb57329">medium</a>.</li><li><strong>Automated backup and restore</strong>: open source <a href="https://databasus.com/">platform</a>.</li><li><strong>Backup and restore</strong>: on <a href="https://www.crunchydata.com/blog/introduction-to-postgres-backups">crunchy data</a>.</li></ul><h3>13. Next Part</h3><p><strong>Part 7 moves into indexing, starting with the B-Tree.</strong></p><p>We cover what actually happens inside PostgreSQL when you run CREATE INDEX, why a B-Tree is the default for almost everything, and the query patterns where an index you added with good intentions never gets used at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=045e5cbba27f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL on AWS: Provision, Configure, and Connect, No Console Clicks Required | Part 5]]></title>
            <link>https://imehboob.medium.com/postgresql-on-aws-provision-configure-and-connect-no-console-clicks-required-part-5-e6c86534455c?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c86534455c</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 03:50:14 GMT</pubDate>
            <atom:updated>2026-07-07T03:50:14.155Z</atom:updated>
            <content:encoded><![CDATA[<p><em>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoaJ-WcjN7ST0YZ_G7m8xg.png" /><figcaption><em>image credit: OpenAI</em></figcaption></figure><h3>Table of Contents</h3><ul><li><strong>Quick Recap of Part 4</strong></li><li><strong>Who This Is For</strong></li><li><strong>What You Will Have Built by the End of Part 5</strong></li></ul><ol><li><strong>Why Clicking the Console Is a Bad Habit</strong></li><li><strong>The Infrastructure Design</strong></li></ol><ul><li><strong>A. Two Servers, Two Subnets</strong></li><li><strong>B. The Networking Pieces</strong></li><li><strong>C. Security Groups</strong></li></ul><p><strong>3. Setting Up AWS CLI and Pulumi</strong></p><ul><li><strong>A. Configure the AWS CLI</strong></li><li><strong>B. Create the Project Directory and Python Environment</strong></li><li><strong>C. Initialize the Pulumi Project</strong></li></ul><p><strong>4. Writing the Infrastructure Code</strong></p><ul><li><strong>A. VPC and Subnets</strong></li><li><strong>B. Gateways and Route Tables</strong></li><li><strong>C. Security Groups</strong></li><li><strong>D. EC2 Instances</strong></li><li><strong>E. The SSH Config Generator</strong></li><li><strong>F. The Full main.py</strong></li></ul><p><strong>5. Create the Key Pair and Provision</strong></p><ul><li><strong>A. Create the AWS Key Pair</strong></li><li><strong>B. Run pulumi up</strong></li><li><strong>C. Verify the SSH Config and Connect</strong></li></ul><p><strong>6. Configure PostgreSQL for Remote Access</strong></p><ul><li><strong>A. Set a Password for the postgres User</strong></li><li><strong>B. Allow Connections from the pgAdmin Subnet</strong></li><li><strong>C. Listen on All Interfaces</strong></li><li><strong>D. Restart and Verify</strong></li></ul><p><strong>7. Run pgAdmin on Docker</strong></p><ul><li><strong>A. Verify Docker Is Running</strong></li><li><strong>B. Start the pgAdmin Container</strong></li><li><strong>C. Access pgAdmin in the Browser</strong></li></ul><p><strong>8. Connect pgAdmin to PostgreSQL</strong></p><p><strong>9. Conclusion</strong></p><p><strong>10. Resources</strong></p><p><strong>11. Next Part</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fq0t4G%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fq0t4G%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fq0t4G%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="1905" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ba6b4a99119ee94f3e836ee8e0d95f/href">https://medium.com/media/08ba6b4a99119ee94f3e836ee8e0d95f/href</a></iframe><h3>Quick Recap of Part 4</h3><p><a href="https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917?sharedUserId=imehboob">In Part 4</a>, we moved upstream from queries into schema design. We built a 5-table e-commerce schema from scratch: users, products, orders, order_items, and payments.</p><p>We looked at why the flat orders table from <strong>Parts 1–3</strong> could not handle a real cart, seeded the schema with 16,500 rows using a Python script, and ran 8 production-pattern queries, including a CTE and a window function.</p><p>The point of Part 4 was that a good schema makes queries simple. A bad schema turns every query into a workaround.</p><p><strong>If you have not done </strong><a href="https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917?sharedUserId=imehboob"><strong>Part 4</strong></a><strong> yet, start there first: </strong><a href="https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917"><strong>Part 4: The Ecommerce Database</strong></a></p><p>In this part, we take PostgreSQL off your local machine and put it on AWS. The schema stays the same. The address changes. And we learn how to do all of it with code, not clicks.</p><h3>Who This Is For</h3><p>This part is tagged <strong>[Intermediate]</strong>.</p><p>You need <strong>Parts 1–4 complete</strong>. You need an AWS account with access keys. No prior experience with Pulumi or Infrastructure as Code is required.</p><p><strong>If you are starting fresh, confirm your environment from </strong><a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2?sharedUserId=imehboob"><strong>Part 1</strong></a><strong> is still working:</strong></p><pre>psql -U testuser -d testdb</pre><p>That is the only check we need before moving forward.</p><h3>What You Will Have Built by the End of Part 5</h3><p><strong>By the time you close this tab, you will have:</strong></p><ul><li><strong>Provisioned a complete AWS network from a Python file</strong>: VPC, public and private subnets, Internet Gateway, NAT Gateway, route tables, and two EC2 instances</li><li><strong>Launched a PostgreSQL database server in a private subnet</strong> with no public IP, and a pgAdmin server in a public subnet reachable from the browser</li><li><strong>Configured PostgreSQL to accept remote connections from inside the VPC</strong>, without exposing port 5432 to the internet</li><li><strong>Run pgAdmin in a Docker container</strong> and connected it to the private PostgreSQL server across the VPC</li><li><strong>Verified the full setup by running a live query</strong> from the pgAdmin browser interface</li></ul><blockquote>okey, so let’s start.</blockquote><h3>1. Why Clicking the Console Is a Bad Habit</h3><p>Every engineer who has worked on AWS has done this.</p><p>You log in to the console. You click “Launch Instance.” You pick a subnet, configure the security group through the dropdowns, paste some user data in the box, and fifteen minutes later you have a running EC2 instance.</p><p>It works. The instance is real.</p><p>Then three weeks later someone asks you to spin up the same environment for staging.</p><p><strong>Which security group rules did you set?</strong></p><p><strong>What user data did you give the instance?</strong></p><p><strong>Which subnet?</strong></p><p><strong>Which AMI?</strong></p><p>You do not remember. There is no file. There is no history. You click through the wizard again and hope it matches.</p><p>This is the problem Infrastructure as Code solves. Not speed. Not elegance.</p><p><strong>Reproducibility.</strong></p><p>When your infrastructure is code, it is version-controlled. It is reviewable. It is repeatable. If it worked once, running the same file produces the same result every time, on a different account, in a different region, six months from now.</p><blockquote><strong><em>Pulumi is Infrastructure as Code written in Go and Python.</em></strong></blockquote><blockquote><strong><em>You write Python. Pulumi talks to AWS.</em></strong></blockquote><blockquote><strong><em>The AWS console exists. You just do not need to touch it.</em></strong></blockquote><h3>2. The Infrastructure Design</h3><p>Before writing any code, understand what we are building and why it is structured the way it is.</p><h4>A. Two Servers, Two Subnets</h4><p>The PostgreSQL database server lives in a <strong>private subnet</strong>. It has no public IP. Nothing from the internet can reach it directly.</p><p>The pgAdmin server lives in a <strong>public subnet</strong>. It has a public IP. You access the pgAdmin UI from your browser using that IP.</p><p>pgAdmin talks to PostgreSQL over the private network inside the VPC.</p><p><strong>The database never touches the internet.</strong></p><p>That is not a coincidence. That is the design.</p><h4>B. The Networking Pieces</h4><p><strong>VPC: </strong>a vpc is a private network boundary on AWS. Nothing outside enters unless you explicitly allow it.</p><p><strong>Internet Gateway:</strong> it connects the public subnet to the internet. The pgAdmin server needs this to be reachable from your browser.</p><p><strong>NAT Gateway:</strong> NAT sits in the public subnet and lets the private subnet make outbound requests, like apt install postgresql, without being reachable from outside. The database server can call out. Nobody outside can call in.</p><p><strong>Route Tables:</strong> the rules that control where traffic goes. The public subnet routes outbound traffic through the Internet Gateway. The private subnet routes outbound traffic through the NAT Gateway.</p><h4>C. Security Groups</h4><p>Security groups are stateful firewalls attached to EC2 instances.</p><p><strong>pgAdmin security group:</strong> allows SSH on port 22 from anywhere (so you can get in), and HTTP on port 80 from anywhere (for the browser UI). All outbound traffic is allowed.</p><p><strong>PostgreSQL security group:</strong> allows SSH only from the public subnet CIDR (10.0.1.0/24), and port 5432 only from the public subnet CIDR. Nothing else.</p><blockquote>Port 5432 is not open to<em> </em><em>0.0.0.0/0</em>.</blockquote><blockquote>It is open only to<em> </em><em>10.0.1.0/24, </em>the subnet where the pgAdmin server lives.</blockquote><blockquote>That means only the pgAdmin server can talk to PostgreSQL on that port.</blockquote><blockquote><strong>The internet cannot. The security group enforces this at the network level before any application code runs.</strong></blockquote><h3>3. Setting Up AWS CLI and Pulumi</h3><h4>A. Configure the AWS CLI</h4><p>The AWS CLI lets Pulumi authenticate and provision resources on your behalf. We’ll configure it first.</p><p><strong>Run the configure command:</strong></p><pre>aws configure</pre><p>You will be prompted for four values:</p><ul><li><strong>AWS Access Key ID:</strong> your access key to authenticate API requests</li><li><strong>AWS Secret Access Key:</strong> the secret key paired with it</li><li><strong>Default region:</strong> use ap-southeast-1 for this lab</li><li><strong>Default output format:</strong> use json</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*FznaWa8_xpqGHdbOdP2wYA.png" /><figcaption>aws configure</figcaption></figure><h4>B. Create the Project Directory and Python Environment</h4><p><strong>Create a dedicated directory for the infrastructure files:</strong></p><pre>mkdir db-infra<br>cd db-infra</pre><p><strong>Install Python venv:</strong></p><pre>sudo apt update<br>sudo apt install python3.12-venv -y</pre><h4>C. Initialize the Pulumi Project</h4><p><strong>Install Pulumi:</strong></p><pre># Install <br>curl -fsSL https://get.pulumi.com | sh<br><br># Update path and shell restart (Ubuntu)<br>echo &#39;export PATH=$PATH:$HOME/.pulumi/bin&#39; &gt;&gt; ~/.bashrc<br>source ~/.bashrc<br><br># Check if installed <br>pulumi version <br></pre><p><strong>Log in to Pulumi:</strong></p><pre>pulumi login</pre><p>This will prompt for a Pulumi token. Generate one from <a href="https://app.pulumi.com/">app.pulumi.com</a> under your account settings. Paste it in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TUPBoSEGd3ugzID8l1dTEg.png" /><figcaption>pulumi login</figcaption></figure><p><strong>Initialize a new Python-based AWS project:</strong></p><pre>pulumi new aws-python</pre><p>You will see a series of prompts. Accept the defaults for everything except the region. When it asks for the AWS region, type ap-southeast-1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*c6obkOt9Lx809NyIVneliA.png" /><figcaption>pulumi python environment setup complete</figcaption></figure><p>Pulumi sets up the project directory, creates a virtual environment, and installs the base dependencies automatically.</p><blockquote><strong>NOTE:</strong></blockquote><blockquote>Pulumi creates a virtual environment as part of pulumi new. You do not need to activate it separately. Every pulumi command you run from this directory uses it automatically.</blockquote><h3>4. Writing the Infrastructure Code</h3><p>Open the __main__.py file Pulumi generated and replace its entire contents with the code in this section. We walk through each piece before showing the full file.</p><h4>A. VPC and Subnets</h4><p>The VPC is the network boundary. Everything else lives inside it.</p><pre>vpc = aws.ec2.Vpc(<br>    &#39;postgres-db-vpc&#39;,<br>    cidr_block=&#39;10.0.0.0/16&#39;,<br>    enable_dns_support=True,<br>    enable_dns_hostnames=True,<br>    tags={&#39;Name&#39;: &#39;postgres-db-vpc&#39;}<br>)</pre><p>Two subnets: one public for pgAdmin, one private for PostgreSQL.</p><pre>public_subnet = aws.ec2.Subnet(<br>    &#39;postgres-db-public-subnet&#39;,<br>    vpc_id=vpc.id,<br>    cidr_block=&#39;10.0.1.0/24&#39;,<br>    map_public_ip_on_launch=True,<br>    availability_zone=&#39;ap-southeast-1a&#39;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-public-subnet&#39;}<br>)</pre><pre>private_subnet = aws.ec2.Subnet(<br>    &#39;postgres-db-private-subnet&#39;,<br>    vpc_id=vpc.id,<br>    cidr_block=&#39;10.0.2.0/24&#39;,<br>    map_public_ip_on_launch=False,<br>    availability_zone=&#39;ap-southeast-1a&#39;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-private-subnet&#39;}<br>)</pre><p>map_public_ip_on_launch=True on the public subnet means any instance launched there gets a public IP automatically. The private subnet does not get one, by design.</p><h4>B. Gateways and Route Tables</h4><pre>internet_gateway = aws.ec2.InternetGateway(<br>    &#39;postgres-db-internet-gateway&#39;,<br>    vpc_id=vpc.id,<br>    tags={&#39;Name&#39;: &#39;postgres-db-internet-gateway&#39;}<br>)</pre><pre>elastic_ip = aws.ec2.Eip(&#39;nat-eip&#39;)</pre><pre>nat_gateway = aws.ec2.NatGateway(<br>    &#39;postgres-db-nat-gateway&#39;,<br>    allocation_id=elastic_ip.id,<br>    subnet_id=public_subnet.id,<br>    tags={&#39;Name&#39;: &#39;postgres-db-nat-gateway&#39;}<br>)</pre><p>The NAT Gateway lives in the public subnet. It needs an Elastic IP to give it a stable public address for outbound traffic from the private subnet.</p><pre>public_route_table = aws.ec2.RouteTable(<br>    &#39;postgres-db-public-route-table&#39;,<br>    vpc_id=vpc.id,<br>    routes=[<br>        aws.ec2.RouteTableRouteArgs(<br>            cidr_block=&#39;0.0.0.0/0&#39;,<br>            gateway_id=internet_gateway.id,<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-public-route-table&#39;}<br>)</pre><pre>private_route_table = aws.ec2.RouteTable(<br>    &#39;postgres-db-private-route-table&#39;,<br>    vpc_id=vpc.id,<br>    routes=[<br>        aws.ec2.RouteTableRouteArgs(<br>            cidr_block=&#39;0.0.0.0/0&#39;,<br>            nat_gateway_id=nat_gateway.id,<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-private-route-table&#39;}<br>)</pre><pre>public_route_table_association = aws.ec2.RouteTableAssociation(<br>    &#39;postgres-db-public-route-table-association&#39;,<br>    subnet_id=public_subnet.id,<br>    route_table_id=public_route_table.id<br>)</pre><pre>private_route_table_association = aws.ec2.RouteTableAssociation(<br>    &#39;postgres-db-private-route-table-association&#39;,<br>    subnet_id=private_subnet.id,<br>    route_table_id=private_route_table.id<br>)</pre><p>Public subnet routes to the Internet Gateway. Private subnet routes to the NAT Gateway. Each association links the subnet to its correct route table.</p><h4>C. Security Groups</h4><pre>pgadmin_security_group = aws.ec2.SecurityGroup(<br>    &#39;pgadmin-security-group&#39;,<br>    vpc_id=vpc.id,<br>    description=&quot;Security group for pgadmin application&quot;,<br>    ingress=[<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=22, to_port=22,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        ),<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=80, to_port=80,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        ),<br>    ],<br>    egress=[<br>        aws.ec2.SecurityGroupEgressArgs(<br>            protocol=&#39;-1&#39;, from_port=0, to_port=0,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;pgadmin-security-group&#39;}<br>)</pre><pre>postgres_db_security_group = aws.ec2.SecurityGroup(<br>    &#39;postgres-db-security-group&#39;,<br>    vpc_id=vpc.id,<br>    description=&quot;Security group for PostgreSQL database&quot;,<br>    ingress=[<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=22, to_port=22,<br>            cidr_blocks=[public_subnet.cidr_block],<br>        ),<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=5432, to_port=5432,<br>            cidr_blocks=[public_subnet.cidr_block],<br>        ),<br>    ],<br>    egress=[<br>        aws.ec2.SecurityGroupEgressArgs(<br>            protocol=&#39;-1&#39;, from_port=0, to_port=0,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-security-group&#39;}<br>)</pre><p>The PostgreSQL security group uses public_subnet.cidr_block instead of a hardcoded string. This keeps the code consistent: if the subnet CIDR ever changes, the security group rule updates with it automatically.</p><h4>D. EC2 Instances</h4><p>The database server installs PostgreSQL through user data. The pgAdmin server installs Docker.</p><pre>db = aws.ec2.Instance(<br>    &#39;db-server&#39;,<br>    instance_type=instance_type,<br>    ami=ami,<br>    subnet_id=private_subnet.id,<br>    key_name=&quot;db-cluster&quot;,<br>    vpc_security_group_ids=[postgres_db_security_group.id],<br>    user_data_replace_on_change=True,<br>    user_data=&quot;&quot;&quot;#!/bin/bash<br>    sudo apt update<br>    sudo apt install -y postgresql postgresql-contrib<br>    sudo systemctl start postgresql<br>    sudo systemctl enable postgresql<br>    &quot;&quot;&quot;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-server&#39;},<br>    opts=pulumi.ResourceOptions(<br>        depends_on=[<br>            nat_gateway,<br>            private_route_table_association,<br>            private_subnet<br>        ]<br>    )<br>)</pre><pre>pgadmin = aws.ec2.Instance(<br>    &#39;pgadmin-server&#39;,<br>    instance_type=instance_type,<br>    ami=ami,<br>    subnet_id=public_subnet.id,<br>    key_name=&quot;db-cluster&quot;,<br>    vpc_security_group_ids=[pgadmin_security_group.id],<br>    associate_public_ip_address=True,<br>    user_data_replace_on_change=True,<br>    user_data=&quot;&quot;&quot;#!/bin/bash<br>    sudo apt update<br>    sudo apt install -y docker.io<br>    sudo systemctl enable docker<br>    sudo systemctl start docker<br>    &quot;&quot;&quot;,<br>    tags={&#39;Name&#39;: &#39;pgadmin-server&#39;}<br>)</pre><p>The depends_on on the database server is not optional.</p><p>The private subnet instance needs the NAT Gateway to reach the internet to run apt install postgresql. Without that dependency, Pulumi might boot the instance before the NAT Gateway exists. The cloud-init script would fail, PostgreSQL would not be installed, and you would see no error message telling you why.</p><blockquote><strong>NOTE:</strong></blockquote><blockquote>The AMI ami-01811d4912b4ccb26 is an Ubuntu image for the ap-southeast-1 region.</blockquote><blockquote>If you are using a different region, look up the equivalent Ubuntu 22.04 AMI for that region in the AWS console under EC2 &gt; AMI Catalog before running this.</blockquote><h4>E. The SSH Config Generator</h4><p>At the end of __main__.py, export the IPs and write the SSH config automatically.</p><pre>pulumi.export(&#39;pgadmin_public_ip&#39;, pgadmin.public_ip)<br>pulumi.export(&#39;pgadmin_private_ip&#39;, pgadmin.private_ip)<br>pulumi.export(&#39;postgres_db_private_ip&#39;, db.private_ip)<br>pulumi.export(&#39;vpc_id&#39;, vpc.id)<br>pulumi.export(&#39;public_subnet_id&#39;, public_subnet.id)<br>pulumi.export(&#39;private_subnet_id&#39;, private_subnet.id)</pre><pre>def create_config_file(all_ips):<br>    config_content = f&quot;&quot;&quot;Host pgadmin-server<br>    HostName {all_ips[0]}<br>    User ubuntu<br>    IdentityFile ~/.ssh/db-cluster.id_rsa</pre><pre>Host postgres-db-server<br>    ProxyJump pgadmin-server<br>    HostName {all_ips[1]}<br>    User ubuntu<br>    IdentityFile ~/.ssh/db-cluster.id_rsa<br>&quot;&quot;&quot;<br>    config_path = os.path.expanduser(&quot;~/.ssh/config&quot;)<br>    with open(config_path, &quot;w&quot;) as config_file:<br>        config_file.write(config_content)</pre><pre>all_ips = [pgadmin.public_ip, db.private_ip]<br>pulumi.Output.all(*all_ips).apply(create_config_file)</pre><p>The ProxyJump pgadmin-server line is what makes ssh postgres-db-server work directly from your local machine. SSH sees the config, routes through the pgAdmin server transparently, and lands you on the database server. You never have to SSH into pgAdmin manually just to hop over to the database.</p><h4>F. The Full main.py</h4><p><strong>Replace the contents of </strong><strong>__main__.py with this complete file:</strong></p><pre>import pulumi<br>import pulumi_aws as aws<br>import os</pre><pre>instance_type = &#39;t2.micro&#39;<br>ami = &#39;ami-01811d4912b4ccb26&#39;</pre><pre>vpc = aws.ec2.Vpc(<br>    &#39;postgres-db-vpc&#39;,<br>    cidr_block=&#39;10.0.0.0/16&#39;,<br>    enable_dns_support=True,<br>    enable_dns_hostnames=True,<br>    tags={&#39;Name&#39;: &#39;postgres-db-vpc&#39;}<br>)</pre><pre>public_subnet = aws.ec2.Subnet(<br>    &#39;postgres-db-public-subnet&#39;,<br>    vpc_id=vpc.id,<br>    cidr_block=&#39;10.0.1.0/24&#39;,<br>    map_public_ip_on_launch=True,<br>    availability_zone=&#39;ap-southeast-1a&#39;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-public-subnet&#39;}<br>)</pre><pre>private_subnet = aws.ec2.Subnet(<br>    &#39;postgres-db-private-subnet&#39;,<br>    vpc_id=vpc.id,<br>    cidr_block=&#39;10.0.2.0/24&#39;,<br>    map_public_ip_on_launch=False,<br>    availability_zone=&#39;ap-southeast-1a&#39;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-private-subnet&#39;}<br>)</pre><pre>internet_gateway = aws.ec2.InternetGateway(<br>    &#39;postgres-db-internet-gateway&#39;,<br>    vpc_id=vpc.id,<br>    tags={&#39;Name&#39;: &#39;postgres-db-internet-gateway&#39;}<br>)</pre><pre>elastic_ip = aws.ec2.Eip(&#39;nat-eip&#39;)</pre><pre>nat_gateway = aws.ec2.NatGateway(<br>    &#39;postgres-db-nat-gateway&#39;,<br>    allocation_id=elastic_ip.id,<br>    subnet_id=public_subnet.id,<br>    tags={&#39;Name&#39;: &#39;postgres-db-nat-gateway&#39;}<br>)</pre><pre>public_route_table = aws.ec2.RouteTable(<br>    &#39;postgres-db-public-route-table&#39;,<br>    vpc_id=vpc.id,<br>    routes=[<br>        aws.ec2.RouteTableRouteArgs(<br>            cidr_block=&#39;0.0.0.0/0&#39;,<br>            gateway_id=internet_gateway.id,<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-public-route-table&#39;}<br>)</pre><pre>private_route_table = aws.ec2.RouteTable(<br>    &#39;postgres-db-private-route-table&#39;,<br>    vpc_id=vpc.id,<br>    routes=[<br>        aws.ec2.RouteTableRouteArgs(<br>            cidr_block=&#39;0.0.0.0/0&#39;,<br>            nat_gateway_id=nat_gateway.id,<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-private-route-table&#39;}<br>)</pre><pre>public_route_table_association = aws.ec2.RouteTableAssociation(<br>    &#39;postgres-db-public-route-table-association&#39;,<br>    subnet_id=public_subnet.id,<br>    route_table_id=public_route_table.id<br>)</pre><pre>private_route_table_association = aws.ec2.RouteTableAssociation(<br>    &#39;postgres-db-private-route-table-association&#39;,<br>    subnet_id=private_subnet.id,<br>    route_table_id=private_route_table.id<br>)</pre><pre>pgadmin_security_group = aws.ec2.SecurityGroup(<br>    &#39;pgadmin-security-group&#39;,<br>    vpc_id=vpc.id,<br>    description=&quot;Security group for pgadmin application&quot;,<br>    ingress=[<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=22, to_port=22,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        ),<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=80, to_port=80,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        ),<br>    ],<br>    egress=[<br>        aws.ec2.SecurityGroupEgressArgs(<br>            protocol=&#39;-1&#39;, from_port=0, to_port=0,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;pgadmin-security-group&#39;}<br>)</pre><pre>postgres_db_security_group = aws.ec2.SecurityGroup(<br>    &#39;postgres-db-security-group&#39;,<br>    vpc_id=vpc.id,<br>    description=&quot;Security group for PostgreSQL database&quot;,<br>    ingress=[<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=22, to_port=22,<br>            cidr_blocks=[public_subnet.cidr_block],<br>        ),<br>        aws.ec2.SecurityGroupIngressArgs(<br>            protocol=&#39;tcp&#39;, from_port=5432, to_port=5432,<br>            cidr_blocks=[public_subnet.cidr_block],<br>        ),<br>    ],<br>    egress=[<br>        aws.ec2.SecurityGroupEgressArgs(<br>            protocol=&#39;-1&#39;, from_port=0, to_port=0,<br>            cidr_blocks=[&#39;0.0.0.0/0&#39;],<br>        )<br>    ],<br>    tags={&#39;Name&#39;: &#39;postgres-db-security-group&#39;}<br>)</pre><pre>db = aws.ec2.Instance(<br>    &#39;db-server&#39;,<br>    instance_type=instance_type,<br>    ami=ami,<br>    subnet_id=private_subnet.id,<br>    key_name=&quot;db-cluster&quot;,<br>    vpc_security_group_ids=[postgres_db_security_group.id],<br>    user_data_replace_on_change=True,<br>    user_data=&quot;&quot;&quot;#!/bin/bash<br>    sudo apt update<br>    sudo apt install -y postgresql postgresql-contrib<br>    sudo systemctl start postgresql<br>    sudo systemctl enable postgresql<br>    &quot;&quot;&quot;,<br>    tags={&#39;Name&#39;: &#39;postgres-db-server&#39;},<br>    opts=pulumi.ResourceOptions(<br>        depends_on=[nat_gateway, private_route_table_association, private_subnet]<br>    )<br>)</pre><pre>pgadmin = aws.ec2.Instance(<br>    &#39;pgadmin-server&#39;,<br>    instance_type=instance_type,<br>    ami=ami,<br>    subnet_id=public_subnet.id,<br>    key_name=&quot;db-cluster&quot;,<br>    vpc_security_group_ids=[pgadmin_security_group.id],<br>    associate_public_ip_address=True,<br>    user_data_replace_on_change=True,<br>    user_data=&quot;&quot;&quot;#!/bin/bash<br>    sudo apt update<br>    sudo apt install -y docker.io<br>    sudo systemctl enable docker<br>    sudo systemctl start docker<br>    &quot;&quot;&quot;,<br>    tags={&#39;Name&#39;: &#39;pgadmin-server&#39;}<br>)</pre><pre>pulumi.export(&#39;pgadmin_public_ip&#39;, pgadmin.public_ip)<br>pulumi.export(&#39;pgadmin_private_ip&#39;, pgadmin.private_ip)<br>pulumi.export(&#39;postgres_db_private_ip&#39;, db.private_ip)<br>pulumi.export(&#39;vpc_id&#39;, vpc.id)<br>pulumi.export(&#39;public_subnet_id&#39;, public_subnet.id)<br>pulumi.export(&#39;private_subnet_id&#39;, private_subnet.id)</pre><pre>def create_config_file(all_ips):<br>    config_content = f&quot;&quot;&quot;Host pgadmin-server<br>    HostName {all_ips[0]}<br>    User ubuntu<br>    IdentityFile ~/.ssh/db-cluster.id_rsa</pre><pre>Host postgres-db-server<br>    ProxyJump pgadmin-server<br>    HostName {all_ips[1]}<br>    User ubuntu<br>    IdentityFile ~/.ssh/db-cluster.id_rsa<br>&quot;&quot;&quot;<br>    config_path = os.path.expanduser(&quot;~/.ssh/config&quot;)<br>    with open(config_path, &quot;w&quot;) as config_file:<br>        config_file.write(config_content)</pre><pre>all_ips = [pgadmin.public_ip, db.private_ip]<br>pulumi.Output.all(*all_ips).apply(create_config_file)</pre><h3>5. Create the Key Pair and Provision</h3><h4>A. Create the AWS Key Pair</h4><p>Both EC2 instances are configured to use a key named db-cluster. That key must exist in AWS <strong>before</strong> you run pulumi up. If it does not exist, the instances boot, but you will never be able to SSH in. No error during provisioning will tell you this.</p><p><strong>Create the key pair and save it locally:</strong></p><pre>cd ~/.ssh/<br>aws ec2 create-key-pair --key-name db-cluster --output text --query &#39;KeyMaterial&#39; &gt; db-cluster.id_rsa<br>chmod 400 db-cluster.id_rsa</pre><p>chmod 400 restricts the file to read-only by the owner. SSH refuses to use a key file with open permissions and gives you a confusing error about it. Just set this now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Rc13N32KYFl5lTuO3fxfLA.png" /><figcaption>ssh key create</figcaption></figure><h4>B. Run pulumi up</h4><p><strong>Navigate back to the project directory and provision:</strong></p><pre>cd ~/db-infra<br>pulumi up --yes</pre><p>Pulumi will show a preview and then begin creating resources in dependency order. The NAT Gateway takes the longest. Expect 3 to 5 minutes for the full run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*PTN3LW1NLfsBOcuRAX4D1Q.png" /><figcaption>resources in create state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*EsI1Kunc7ha1MdC7haI7lA.png" /><figcaption>all resources created</figcaption></figure><h4>C. Verify the SSH Config and Connect</h4><p><strong>Check the SSH config was written correctly:</strong></p><pre>cat ~/.ssh/config</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*xvLQkakNgl9D-ULPXUNBkw.png" /><figcaption>ssh config</figcaption></figure><p>You should see two blocks. pgadmin-server with the public IP. postgres-db-server with the private IP and ProxyJump pgadmin-server.</p><p><strong>SSH into the pgAdmin server:</strong></p><pre>ssh pgadmin-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*QPOsQ8mQ5AJv-XZaTHMXig.png" /><figcaption>ssh to pgadmin server (the public subnet)</figcaption></figure><p><strong>Open a second terminal and SSH into the database server:</strong></p><pre>ssh postgres-db-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*jl9WZEMYv7ekZvLQRq-Iew.png" /><figcaption>ssh to the db server in private subnet</figcaption></figure><p>This connection went through the <strong>pgAdmin server automatically</strong>. The SSH config handled the jump. You did not touch pgAdmin manually to get there.</p><blockquote><strong>NOTE:</strong></blockquote><blockquote>Optionally, rename the hostnames to make them easier to tell apart in your terminal:</blockquote><blockquote>On the pgAdmin server:<em> </em><em>sudo hostnamectl set-hostname pg-admin</em></blockquote><blockquote>On the db server:<em> </em><em>sudo hostnamectl set-hostname db-server</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*rjxWV8rj3OmCTQZpf2Yv4A.png" /><figcaption>chagend the name of db server for better management</figcaption></figure><blockquote>This is cosmetic. It changes nothing about how the servers work.</blockquote><h3>6. Configure PostgreSQL for Remote Access</h3><p>You are now on the database server. PostgreSQL is installed and running, but it is only listening on localhost and only accepting local connections. Two files need to be edited to change that: pg_hba.conf for authentication rules, and postgresql.conf for the listen address.</p><p><strong>Do these in order. The password comes first.</strong></p><h4>A. Set a Password for the postgres User in db-server</h4><p>By default, PostgreSQL uses peer authentication locally. This means the postgres Linux system user can log into the postgres database user without a password. That is fine for local access.</p><p>But when pgAdmin connects from a different IP, it cannot use peer auth. It needs a password. If you change pg_hba.conf to require password-based auth before setting a password, you lock yourself out of your own psql session.</p><p><strong>Check that the cloud-init script finished successfully:</strong></p><pre>cat /var/log/cloud-init-output.log</pre><p>Scroll to the bottom. PostgreSQL installation should be complete with no errors. If it is still running, wait a minute and check again.</p><p><strong>Switch to the postgres system user and open psql:</strong></p><pre>sudo -u postgres psql</pre><p><strong>Set a password for the postgres database user:</strong></p><pre>ALTER USER postgres PASSWORD &#39;postgres&#39;;</pre><p><strong>Exit psql:</strong></p><pre>\q</pre><p>Password is set. Now you can safely change the auth method.</p><h4>B. Allow Connections from the pgAdmin Subnet</h4><p><strong>Open pg_hba.conf:</strong></p><pre>sudo vim /etc/postgresql/*/main/pg_hba.conf</pre><p>Scroll to the bottom of the file and add this line:</p><pre>host    all             all             10.0.1.0/24           scram-sha-256</pre><p>10.0.1.0/24 is the CIDR of the public subnet where the pgAdmin server lives. md5 means password-based authentication. Save and exit.</p><blockquote><strong>NOTE:</strong></blockquote><blockquote>The * in /etc/postgresql/*/main/pg_hba.conf matches the PostgreSQL version number installed on your system, for example /etc/postgresql/14/main/pg_hba.conf. The glob works in most shells.</blockquote><blockquote>If you are not sure which version is installed, run psql --version before opening the file.</blockquote><h4>C. Listen on All Interfaces</h4><p>By default, PostgreSQL listens only on localhost. The pgAdmin server connects from a different IP inside the VPC, so PostgreSQL needs to accept connections on all network interfaces.</p><p><strong>Open postgresql.conf:</strong></p><pre>sudo vim /etc/postgresql/*/main/postgresql.conf</pre><p>Find the listen_addresses line. It will look like this, possibly commented out:</p><pre>#listen_addresses = &#39;localhost&#39;</pre><p><strong>Change it to:</strong></p><pre>listen_addresses = &#39;*&#39;</pre><p>Save and exit.</p><blockquote>listen_addresses = &#39;*&#39; does not mean the database is open to the internet.</blockquote><blockquote>It means PostgreSQL will accept connections on all network interfaces of the server.</blockquote><blockquote>The security group still controls which source IPs can actually reach port 5432.</blockquote><blockquote><strong>The security group is the lock. </strong><strong>listen_addresses just tells PostgreSQL to stand at the door instead of hiding in the back room.</strong></blockquote><h4>D. Restart and Verify</h4><p><strong>Restart PostgreSQL to apply both config changes:</strong></p><pre>sudo systemctl restart postgresql</pre><p><strong>Check the status:</strong></p><pre>sudo systemctl status &quot;postgresql@*&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbpeRSQRRwvsHAs_GCzFIQ.png" /><figcaption>postgresql running</figcaption></figure><p>active (running) means it came back up cleanly with the new configuration. PostgreSQL is now listening on all interfaces and will accept password-authenticated connections from 10.0.1.0/24.</p><h3>7. Run pgAdmin on Docker</h3><p>Open a new terminal on your local machine. SSH into the pgAdmin server.</p><pre>ssh pgadmin-server</pre><h4>A. Verify Docker Is Running</h4><p><strong>Check the cloud-init logs:</strong></p><pre>cat /var/log/cloud-init-output.log</pre><p>Look for Docker installation completing without errors.</p><p><strong>Confirm Docker is active:</strong></p><pre>sudo systemctl status docker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*VP2Zg9rkp8Un0tCePlMiXQ.png" /><figcaption>docker running in pgadmin server</figcaption></figure><p>Docker is running. You can start a container.</p><h4>B. Start the pgAdmin Container</h4><p><strong>Run pgAdmin as a Docker container on port 80:</strong></p><pre>sudo docker run -d \<br>    --name pgadmin \<br>    -p 80:80 \<br>    -e PGADMIN_DEFAULT_EMAIL=admin@admin.com \<br>    -e PGADMIN_DEFAULT_PASSWORD=admin \<br>    dpage/pgadmin4</pre><p>The first run pulls the dpage/pgadmin4 image, about 300MB. After the pull, the container starts in detached mode (-d) and Docker prints the container ID.</p><p>Replace admin@admin.com and admin with your own credentials if you prefer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*tTMLzhbRPuHItRlK2EQ_lQ.png" /><figcaption>pgadmin docker running</figcaption></figure><h4>C. Access pgAdmin in the Browser</h4><p><strong>Open your browser and navigate to:</strong></p><pre>http://&lt;pgadmin_public_ip&gt;</pre><p>Use the public IP from the pulumi up output, or read it from cat ~/.ssh/config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnQ-NcWPQbnuAmzLzGar3w.png" /><figcaption>pgadmin login through public IP</figcaption></figure><p>Log in with the credentials you set in the Docker run command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5IZeRP9s0XJ4GVszxmA_g.png" /><figcaption>login to pgadmin through browser</figcaption></figure><h3>8. Connect pgAdmin to PostgreSQL</h3><p><strong>In the pgAdmin left sidebar, right-click “Servers” and select “Register &gt; Server”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*bizOiACFxX6PwjmMW680bw.png" /><figcaption>register server</figcaption></figure><p><strong>In the “General” tab, give the server a name.</strong></p><p>Something like PostgreSQL Server or Part 5 DB. This is just the label inside pgAdmin.</p><p><strong>Click the “Connection” tab and fill in the following:</strong></p><ul><li><strong>Hostname/address:</strong> the private IP of the PostgreSQL EC2 instance (from pulumi up output or cat ~/.ssh/config)</li><li><strong>Port:</strong> 5432</li><li><strong>Maintenance database:</strong> postgres</li><li><strong>Username:</strong> postgres</li><li><strong>Password:</strong> postgres (or whatever you set in Section 6A)</li></ul><p><strong>Click “Save.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKQXbD-jDgVOK1x4-PVYjw.png" /><figcaption>connected to the postgres database</figcaption></figure><p><strong>Open the Query Tool and run a test query:</strong></p><pre>SELECT version();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSZvPrKDxBWcyqrCwC0Plg.png" /><figcaption>query run successfully</figcaption></figure><p>The query runs. The version string comes back.</p><p><strong>Add demo student table, and some demo data:</strong></p><pre>CREATE TABLE students (<br>    student_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    email VARCHAR(150) UNIQUE NOT NULL,<br>    roll_number VARCHAR(20) UNIQUE NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);<br><br><br>INSERT INTO students (name, email, roll_number) VALUES<br>(&#39;Alex Johnson&#39;, &#39;alex.j@example.com&#39;, &#39;2026-CS-01&#39;),<br>(&#39;Emily Diaz&#39;, &#39;emily.d@example.com&#39;, &#39;2026-CS-02&#39;),<br>(&#39;Michael Chen&#39;, &#39;michael.c@example.com&#39;, &#39;2026-CS-03&#39;),<br>(&#39;Sophia Martinez&#39;, &#39;sophia.m@example.com&#39;, &#39;2026-CS-04&#39;);</pre><p><strong>Get the data:</strong></p><pre>SELECT * FROM students;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRZR3XE0lp96VgtuyLemjQ.png" /><figcaption>data is returned to the pgadmin from the databae correctly</figcaption></figure><p><strong>Verify the data from database server:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*_1O0kKqiazXer2NBblGNcA.png" /><figcaption>data can also be verified from the database server peer auth</figcaption></figure><blockquote><strong>Your browser is talking to pgAdmin running in Docker on an EC2 instance in a public subnet</strong>.</blockquote><blockquote><strong>pgAdmin is talking to PostgreSQL running on an EC2 instance in a private subnet</strong>.</blockquote><blockquote><strong>The private instance has no public IP. The internet cannot reach the database directly.</strong></blockquote><p><strong>That is the full chain, working.</strong></p><h3>9. Conclusion</h3><p><strong>You provisioned an entire AWS network from a Python file. VPC, subnets, gateways, route tables, security groups, and two EC2 instances, all of it from a single </strong><strong>pulumi up command.</strong></p><p>The PostgreSQL server has no public IP. The internet cannot reach port 5432 directly. But you can query it from a browser, from anywhere in the world, through pgAdmin.</p><p>The thing worth remembering from this part is not any specific command or config line.</p><blockquote>When your infrastructure lives in a file, it can be reviewed, repeated, and trusted.</blockquote><blockquote>When it lives in a series of console clicks from three months ago, it can only be remembered.</blockquote><blockquote><strong>And memory is not version control.</strong></blockquote><p>And get ready for part 6 because we’ll go deeper into the database itself. We cover backup and restore: <strong>how to take a logical dump of your PostgreSQL data, what </strong><strong>pg_dump and </strong><strong>pg_restore actually do</strong>, and how to recover when something goes wrong on a live server.</p><h3>10. Resources</h3><ul><li><strong>Pulumi AWS Documentation:</strong> Full reference for all Pulumi AWS resources including EC2, VPC, and security groups. <a href="https://www.pulumi.com/registry/packages/aws/">pulumi.com/registry/packages/aws</a></li><li><strong>pgAdmin Docker Image Documentation:</strong> Official dpage/pgadmin4 Docker image with all environment variable options. <a href="https://hub.docker.com/r/dpage/pgadmin4">hub.docker.com/r/dpage/pgadmin4</a></li><li><strong>PostgreSQL pg_hba.conf Documentation:</strong> Complete reference for host-based authentication configuration. <a href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">postgresql.org/docs/current/auth-pg-hba-conf.html</a></li><li><strong>AWS VPC Documentation:</strong> How VPCs, subnets, route tables, and gateways work together. <a href="https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html">docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html</a></li><li><strong>Part 4 of this series:</strong> E-commerce schema design, seed data at scale, CTEs, and window functions. <a href="https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917">Part 4</a></li></ul><h3>11. Next Part</h3><p><strong>Part 6 is about backup and restore.</strong></p><p>We cover pg_dump and pg_restore, what a logical backup actually contains, how to restore it to a fresh database, and what to do when the restore needs to go to a different server than where the backup came from. Same database. Different machine. That is where engineers learn whether their backup actually worked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c86534455c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ecommerce Database: How to Design a Schema That Holds Real Data | Part 4]]></title>
            <link>https://imehboob.medium.com/the-ecommerce-database-how-to-design-a-schema-that-holds-real-data-part-4-27f6f6979917?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/27f6f6979917</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Tue, 19 May 2026 17:42:27 GMT</pubDate>
            <atom:updated>2026-05-19T17:42:27.176Z</atom:updated>
            <content:encoded><![CDATA[<p><em>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAW_h7slFjp9Nfg5yYu4cg.png" /><figcaption>image credit: grok</figcaption></figure><h3>Table of Contents</h3><ul><li><strong>Quick Recap of Part 3</strong></li><li><strong>Who This Is For</strong></li><li><strong>What You Will Have Built by the End of Part 4</strong></li></ul><ol><li><strong>Why the Old Schema Breaks</strong></li><li><strong>The ER Diagram: Design Before You Code</strong></li></ol><ul><li><strong>A. The Five Entities</strong></li><li><strong>B. The Relationships</strong></li><li><strong>C. The Junction Table Problem</strong></li></ul><p><strong>3. Creating the Ecommerce Schema</strong></p><ul><li><strong>A. The users Table</strong></li><li><strong>B. The products Table</strong></li><li><strong>C. The orders Table</strong></li><li><strong>D. The order_items Table</strong></li><li><strong>E. The payments Table</strong></li></ul><p><strong>4. Seeding the Database with Realistic Data</strong></p><ul><li><strong>A. Setting Up the Python Environment</strong></li><li><strong>B. The Script</strong></li><li><strong>C. Running It and Verifying</strong></li></ul><p><strong>5. Real Queries Against Real Data</strong></p><ul><li><strong>A. Users Who Placed Orders</strong></li><li><strong>B. Total Revenue by User</strong></li><li><strong>C. Users Who Never Ordered</strong></li><li><strong>D. Top 5 Products by Sales Quantity</strong></li><li><strong>E. Orders With Payment Status</strong></li><li><strong>F. Users Who Spent More Than $1000</strong></li><li><strong>G. Most Recent Order Per User (CTE)</strong></li><li><strong>H. Running Total of Revenue Over Time (Window Function)</strong></li></ul><p><strong>6. Schema Design Gotchas</strong></p><ul><li><strong>A. Snapshot Pricing in order_items</strong></li><li><strong>B. The One-to-One Trap in payments</strong></li><li><strong>C. status as VARCHAR Without a Constraint</strong></li><li><strong>D. The Seed Data total_amount Mismatch</strong></li></ul><p><strong>7. Conclusion</strong></p><p><strong>8. Resources</strong></p><p><strong>9. Next Part</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FS9LoS%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FS9LoS%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FS9LoS%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="1905" frameborder="0" scrolling="no"><a href="https://medium.com/media/010b1a41bbc5d8a068acf92de14b297d/href">https://medium.com/media/010b1a41bbc5d8a068acf92de14b297d/href</a></iframe><h3>Quick Recap of Part 3</h3><p>In Part 3, we added 5 rows to the orders table, bringing it to 10 orders across 4 customers, then used those rows to run every major aggregation pattern in SQL.</p><p>We covered SUM, COUNT, AVG, MAX, and MIN, broke full-table results down with GROUP BY, filtered grouped results with HAVING, and spent real time on why WHERE and HAVING are not interchangeable, including what exactly breaks when you confuse them.</p><p>We also walked through SQL execution order, which is the single mental model that makes every confusing query error suddenly obvious.</p><p><strong>If you have not done Part 3 yet, start there first:</strong> <a href="https://imehboob.medium.com/aggregations-grouping-in-sql-the-queries-behind-every-dashboard-and-report-part-3-9bd1ce9bd6a0"><strong>Part 3: Aggregations &amp; Grouping in SQL</strong></a></p><p>In this part, we move upstream from queries into schema design. Same database engine. But completely different problem.</p><h3>Who This Is For</h3><p>This part is tagged <strong>[Beginner]</strong>.</p><p>You need Parts 1, 2, and 3 complete. Your testuser, testdb, customers, and orders tables from the previous parts can stay exactly where they are. This part creates a brand new database called ecommerce and does not touch anything from previous parts.</p><p><strong>Log in to psql as the postgres user:</strong></p><pre>psql -U postgres</pre><p>That is your starting point. Everything else happens from here. See <a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2"><strong>part 1 for password</strong></a> recall.</p><h3>What You Will Have Built by the End of Part 4</h3><p>By the time you close this tab, you will have:</p><ul><li>Designed a 5-table ecommerce schema (users, products, orders, order_items, payments) with proper foreign keys and constraints, and understood why each table exists separately</li><li>Understood what specific problem breaks if you try to collapse any two of those tables into one</li><li>Seeded the schema with 1000 users, 500 products, 5000 orders, 10,000 order items, and 5000 payments using a Python script</li><li>Run 8 real production-pattern queries against that data, including a CTE and a window function you have not seen anywhere in this series yet</li><li>Caught 4 schema design traps that look correct on paper and produce silent wrong answers in production</li></ul><p>okey, so let’s start.</p><h3>1. Why the Old Schema Breaks</h3><p>The orders table from Parts 1, 2, and 3 looked like this:</p><pre>orders(order_id, customer_id, product, amount, order_date)</pre><p>It worked. We ran JOINs on it. We grouped it. We filtered it with HAVING. The queries made sense on that table.</p><p>But sit with it for a moment.</p><p>The product column is a text string. Laptop. Mouse. Keyboard. One column. One product per row.</p><p><strong>What happens when a customer adds three items to a single cart?</strong></p><p>You create three rows with the same order_id. You duplicate the order date. You duplicate the customer reference. And you still have no way to say &quot;<strong>this one order contained three things</strong>&quot; as a single coherent fact in the database.</p><p>It gets worse.</p><p>The amount column is one number.</p><p>Is that the price of one item?</p><p>The total across all items?</p><p>What if the customer bought 2 units of the same product?</p><p>There is nowhere to store the quantity.</p><blockquote>You are not missing a column.</blockquote><blockquote>You are missing a table.</blockquote><p><strong>This is what this part is about.</strong></p><p>The schema from Parts 1–3 was a teaching tool. Clean, flat, good for learning queries.</p><p>It would not survive a real application for a week.</p><p><strong>This part replaces it with something that could.</strong></p><p>Five tables instead of two. Relationships instead of text columns. Design decisions made before a single query is written.</p><h3>2. The ER Diagram: Design Before You Code</h3><p>Before touching a keyboard, you draw the entities and the lines between them.</p><p>An entity is a thing your system needs to remember.</p><p>A relationship is how two entities connect.</p><p>If you skip this step and go straight to SQL, you will create tables that fight each other by the third sprint.</p><h4>A. The Five Entities</h4><p>Your e-commerce system needs to track five things:</p><ul><li><strong>Users:</strong> the people who register and place orders</li><li><strong>Products:</strong> the items available for purchase</li><li><strong>Orders:</strong> a purchase event initiated by a user</li><li><strong>Order Items:</strong> the individual line items within an order</li><li><strong>Payments:</strong> the payment transaction linked to an order</li></ul><p>Each of these becomes a table. Each tracks one type of fact. Nothing is doubled up.</p><h4>B. The Relationships</h4><p><strong>Users to Orders:</strong> one user can place many orders. Each order belongs to exactly one user. One-to-many.</p><p><strong>Orders to Order Items:</strong> one order can contain many items. Each item belongs to exactly one order. One-to-many.</p><p><strong>Products to Order Items:</strong> one product can appear across many orders. Each order item references exactly one product. One-to-many.</p><p><strong>Orders to Payments:</strong> each order has one payment record. One-to-one.</p><h4>C. The Junction Table Problem</h4><p>The relationship between orders and products is, underneath the surface, a many-to-many.</p><p>One order can have many products. One product can appear in many orders.</p><p>Relational databases cannot directly store a many-to-many relationship between two tables.</p><p>You need a third table that sits between them, one row per combination.</p><p>That table is order_items.</p><blockquote><em>Think of a restaurant bill.</em></blockquote><blockquote><em>The bill header is one row in </em><em>orders: who ordered, what time, what the total was.</em></blockquote><blockquote><em>Each dish on the bill is a separate line item in </em><em>order_items: which product, how many, at what price.</em></blockquote><blockquote><em>The menu is your </em><em>products table.</em></blockquote><blockquote><em>Nobody puts every dish into a single text column on the bill header.</em></blockquote><blockquote><em>They list each dish on its own row.</em></blockquote><p>And here is something order_items does that most people miss the first time they see it.</p><p>It stores the price of the product at the time of purchase. Not a reference to the current price in the products table. The actual number, captured at that moment.</p><blockquote><strong><em>Product prices change.</em></strong></blockquote><blockquote><strong><em>A laptop that costs $1200 today might cost $999 after a sale next quarter.</em></strong></blockquote><blockquote><strong><em>If you store only a</em></strong><em> </em><em>product_id </em><strong><em>in</em></strong><em> </em><em>order_items </em><strong><em>and look up the price dynamically, every catalog update retroactively changes your historical order totals.</em></strong></blockquote><blockquote><strong><em>Your revenue reports from six months ago would produce different numbers than when you first ran them.</em></strong></blockquote><blockquote><strong><em>Store the snapshot. Not the reference.</em></strong></blockquote><h3>3. Creating the Ecommerce Schema</h3><p><strong>Create the new database and connect to it:</strong></p><pre>CREATE DATABASE ecommerce;<br>\c ecommerce</pre><p>Now create the five tables. Foreign keys reference tables that must already exist, so order matters here. Follow the sequence below exactly.</p><h4>A. The users Table</h4><p><strong>Create the users table:</strong></p><pre>CREATE TABLE users (<br>    user_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    email VARCHAR(150) NOT NULL UNIQUE,<br>    phone VARCHAR(20),<br>    address TEXT,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>email is UNIQUE. Two accounts cannot share an email address. The database enforces this before your application ever gets a chance to validate it.</p><p>phone and address allow NULL. Not every user fills in every field. That is realistic behavior.</p><h4>B. The products Table</h4><p><strong>Create the products table:</strong></p><pre>CREATE TABLE products (<br>    product_id SERIAL PRIMARY KEY,<br>    name VARCHAR(200) NOT NULL,<br>    description TEXT,<br>    price DECIMAL(10,2) NOT NULL,<br>    stock_quantity INT NOT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>price and stock_quantity are both NOT NULL. A product with no price or no inventory count is not something you can sell. The schema refuses to accept it.</p><p>description allows NULL. Some catalog items have a description. Some do not.</p><h4>C. The orders Table</h4><p><strong>Create the orders table:</strong></p><pre>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    user_id INT NOT NULL REFERENCES users(user_id),<br>    total_amount DECIMAL(10,2) NOT NULL,<br>    status VARCHAR(50) NOT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>user_id is a foreign key into users. PostgreSQL will reject any order row referencing a user who does not exist in the users table. You cannot place an order as a ghost account.</p><p>status stores pending, completed, or cancelled. It is VARCHAR with no constraint beyond length right now. We will come back to this in the gotchas section.</p><h4>D. The order_items Table</h4><p><strong>Create the order_items table:</strong></p><pre>CREATE TABLE order_items (<br>    order_item_id SERIAL PRIMARY KEY,<br>    order_id INT NOT NULL REFERENCES orders(order_id),<br>    product_id INT NOT NULL REFERENCES products(product_id),<br>    quantity INT NOT NULL,<br>    price DECIMAL(10,2) NOT NULL<br>);</pre><p>Two foreign keys. Both NOT NULL. An order item must belong to a real order and reference a real product. Orphaned line items are not possible.</p><p>price here is the price at purchase time.</p><p>Not a live reference to products.price.</p><p>The snapshot.</p><h4>E. The payments Table</h4><p><strong>Create the payments table:</strong></p><pre>CREATE TABLE payments (<br>    payment_id SERIAL PRIMARY KEY,<br>    order_id INT NOT NULL REFERENCES orders(order_id),<br>    payment_method VARCHAR(50) NOT NULL,<br>    payment_status VARCHAR(50) NOT NULL,<br>    transaction_id VARCHAR(100) NOT NULL UNIQUE,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>transaction_id is UNIQUE. Every payment event is a distinct transaction. The database will not allow you to process the same transaction twice.</p><p>order_id references orders but does not have a UNIQUE constraint. The design intends one-to-one between orders and payments. The schema does not fully enforce it yet. This is one of the four gotchas covered later.</p><p><strong>Verify all five tables were created:</strong></p><pre>\dt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*eZ1XCPBf0HEBRB5rR90YYA.png" /><figcaption>All five tables</figcaption></figure><p><strong>Five tables. Schema is ready.</strong></p><h3>4. Seeding the Database with Realistic Data</h3><p>Five empty tables answer no questions.</p><p>We could insert rows manually like we did in Parts 1–3.</p><p>A handful of users, a few products, a few orders.</p><p>And we would have exactly the same problem we started this part to solve: <strong>a toy dataset that makes everything look fine.</strong></p><p><strong>Aggregation patterns are not interesting on 10 rows. They become interesting on 5000.</strong></p><p>So we generate realistic fake data at scale using a Python script.</p><p>This is not a shortcut. It is the actual way engineering teams seed databases for development, QA, and load testing.</p><p>Faker is a standard library. The script pattern you are about to run is the same one you would find in any serious project’s seed.py.</p><h4>A. Setting Up the Python Environment</h4><p><strong>Install the required system packages:</strong></p><pre>sudo apt update<br>sudo apt install python3-venv python3-pip libpq-dev python3-dev -y</pre><p><strong>Create a virtual environment and activate it:</strong></p><pre>python3 -m venv ecommerce-env<br>source ecommerce-env/bin/activate</pre><p><strong>Install the Python libraries:</strong></p><pre>pip install psycopg2-binary faker</pre><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote><em>Use </em><em>psycopg2-binary instead of </em><em>psycopg2. The binary package does not require compiling from source and installs cleanly on all modern Linux systems.</em></blockquote><blockquote><em>psycopg2 alone will likely fail on Ubuntu 22+ unless you have the full build chain configured correctly.</em></blockquote><h4>B. The Script</h4><p>Create a directory to store the script</p><pre>mdkir ecommerce-db-test<br>cd ecommerce-db-test</pre><p><strong>Save this as </strong><strong>populate_tables.py:</strong></p><p><strong>Important</strong>: You must add the defaultpassword we added in the Part 1, or any other password as you have chosen in the script.</p><pre>import psycopg2<br>from faker import Faker<br>import random</pre><pre>fake = Faker()</pre><pre>conn = psycopg2.connect(<br>    dbname=&quot;ecommerce&quot;,<br>    user=&quot;postgres&quot;,<br>    password=&quot;defaultpassword&quot;,  # replace with the password you set in Part 1<br>    host=&quot;localhost&quot;,<br>    port=&quot;5432&quot;<br>)<br>cursor = conn.cursor()<br></pre><pre>def generate_users(num_users):<br>    used_emails = set()<br>    for _ in range(num_users):<br>        while True:<br>            name = fake.name()<br>            email = fake.email()<br>            if email not in used_emails:<br>                used_emails.add(email)<br>                break<br>        phone = fake.phone_number()[:20]<br>        address = fake.address()<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO users (name, email, phone, address, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (name, email, phone, address, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_users} users.&quot;)<br></pre><pre>def generate_products(num_products):<br>    for _ in range(num_products):<br>        name = fake.word().capitalize() + &quot; &quot; + fake.word().capitalize()<br>        description = fake.sentence()<br>        price = round(random.uniform(10, 1000), 2)<br>        stock_quantity = random.randint(10, 1000)<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO products (name, description, price, stock_quantity, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (name, description, price, stock_quantity, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_products} products.&quot;)<br></pre><pre>def generate_orders(num_orders):<br>    cursor.execute(&quot;SELECT user_id FROM users&quot;)<br>    user_ids = [row[0] for row in cursor.fetchall()]<br>    for _ in range(num_orders):<br>        user_id = random.choice(user_ids)<br>        total_amount = round(random.uniform(10, 1000), 2)<br>        status = random.choice([&#39;pending&#39;, &#39;completed&#39;, &#39;cancelled&#39;])<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO orders (user_id, total_amount, status, created_at) VALUES (%s, %s, %s, %s)&quot;,<br>            (user_id, total_amount, status, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_orders} orders.&quot;)<br></pre><pre>def generate_order_items(num_items):<br>    cursor.execute(&quot;SELECT order_id FROM orders&quot;)<br>    order_ids = [row[0] for row in cursor.fetchall()]<br>    cursor.execute(&quot;SELECT product_id, price FROM products&quot;)<br>    products = cursor.fetchall()<br>    for _ in range(num_items):<br>        order_id = random.choice(order_ids)<br>        product_id, price = random.choice(products)<br>        quantity = random.randint(1, 10)<br>        cursor.execute(<br>            &quot;INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (%s, %s, %s, %s)&quot;,<br>            (order_id, product_id, quantity, price)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_items} order items.&quot;)<br></pre><pre>def generate_payments(num_payments):<br>    cursor.execute(&quot;SELECT order_id FROM orders&quot;)<br>    order_ids = [row[0] for row in cursor.fetchall()]<br>    for _ in range(num_payments):<br>        order_id = random.choice(order_ids)<br>        payment_method = random.choice([&#39;credit_card&#39;, &#39;paypal&#39;, &#39;bank_transfer&#39;])<br>        payment_status = random.choice([&#39;success&#39;, &#39;pending&#39;, &#39;failed&#39;])<br>        transaction_id = fake.uuid4()<br>        created_at = fake.date_time_between(start_date=&quot;-1y&quot;, end_date=&quot;now&quot;)<br>        cursor.execute(<br>            &quot;INSERT INTO payments (order_id, payment_method, payment_status, transaction_id, created_at) VALUES (%s, %s, %s, %s, %s)&quot;,<br>            (order_id, payment_method, payment_status, transaction_id, created_at)<br>        )<br>    conn.commit()<br>    print(f&quot;Inserted {num_payments} payments.&quot;)<br></pre><pre>generate_users(1000)<br>generate_products(500)<br>generate_orders(5000)<br>generate_order_items(10000)<br>generate_payments(5000)</pre><pre>cursor.close()<br>conn.close()</pre><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote><em>Update </em><em>password=&quot;defaultpassword&quot; to match the postgres user password you set in </em><a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2"><em>Part 1.</em></a></blockquote><blockquote><em>If you do not remember it, reset it from the psql shell before running the script: </em><em>ALTER USER postgres WITH PASSWORD &#39;defaultpassword&#39;;</em></blockquote><h4>C. Running It and Verifying</h4><p><strong>Run the script:</strong></p><pre>python3 populate_tables.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-uPICtYnHr7aatarjJngpw.png" /><figcaption>database populated.</figcaption></figure><p><strong>Switch back to psql and verify the row counts:</strong></p><pre>psql -U postgres -d ecommerce</pre><p><strong>Run a count on each table:</strong></p><pre>SELECT COUNT(*) FROM users;<br>SELECT COUNT(*) FROM products;<br>SELECT COUNT(*) FROM orders;<br>SELECT COUNT(*) FROM order_items;<br>SELECT COUNT(*) FROM payments;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*vMhIpcjGg8m_JhXUTxNMyw.png" /><figcaption>updated tables with rows</figcaption></figure><p><strong>16,500 rows across five tables. There is something worth querying now.</strong></p><h3>5. Real Queries Against Real Data</h3><p>The aggregation queries from Part 3 ran against 10 rows.</p><p><strong>These run against 16,500.</strong></p><p>The SQL is the same. The patterns are the same. But the results mean something now.</p><p>The numbers have variance. Edge cases appear naturally. Some users have never placed an order. Some orders have no payment record. Some products have never been purchased at all.</p><p><strong>That is what a real dataset looks like.</strong></p><h4>A. Users Who Placed Orders</h4><p><strong>The WHY</strong></p><p>The most basic question on any e-commerce platform: <strong>who are my active customers?</strong></p><p>Not every registered account. Not everyone who clicked the sign-up link. Only the users who have actually placed an order and interacted with the purchase flow.</p><p>Your marketing team needs this list before running any retention campaign. You do not send re-engagement emails to users who converted last week. And you do not send “come back” emails to users who have never bought anything in the first place.</p><p><strong>Run the query:</strong></p><pre>SELECT u.user_id, u.name, u.email<br>FROM users u<br>JOIN orders o ON u.user_id = o.user_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*y6hU4KLW1QGL4Vo9iiXbBw.png" /><figcaption>more retuened that users are available</figcaption></figure><p>The result has more rows than you have users. INNER JOIN returns one row per matching pair between users and orders. One user with five orders shows up five times.</p><blockquote><em>If your product manager asks “</em><strong><em>how many active users do we have,</em></strong><em>” this query gives the wrong number.</em></blockquote><blockquote><em>It gives you order events, not unique users.</em></blockquote><blockquote><em>For unique users: </em><strong><em>wrap it in a </em></strong><strong><em>COUNT(DISTINCT u.user_id)</em></strong><em>.</em></blockquote><blockquote><strong><em>Know what the business question is actually asking before you read the row count.</em></strong></blockquote><h4>B. Total Revenue by User</h4><p><strong>The WHY</strong></p><p>Every e-commerce business has a small group of customers who generate a disproportionate share of revenue.</p><p>Your growth team cannot identify that group, act on it, or verify whether the pattern holds without first knowing what each customer has spent in total.</p><p>Not per order. Total, across all their orders, all time.</p><p><strong>Run the query:</strong></p><pre>SELECT u.user_id, u.name, SUM(o.total_amount) AS total_revenue<br>FROM users u<br>JOIN orders o ON u.user_id = o.user_id<br>GROUP BY u.user_id, u.name<br>ORDER BY total_revenue DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*PVqDxEz7eCko8JkBkr1Cbg.png" /><figcaption>top rows of user_id, name, total_revenue ordered by spend descending</figcaption></figure><p>The top of the list is your highest-value customers. The bottom is your lowest. With 5000 orders distributed across 1000 users, the spread will be significant.</p><blockquote>The users missing from this result are the ones who registered and never bought anything.</blockquote><blockquote>They are excluded because INNER JOIN has no rows to match them against in<em> </em><em>orders</em>.</blockquote><blockquote>That absence is information.</blockquote><blockquote>We surface it in the next query.</blockquote><h4>C. Users Who Never Ordered</h4><p><strong>The WHY</strong></p><p>Not every registered account converts to a paying customer. Some users sign up, look around, and disappear.</p><p>Your growth team wants this list for a re-engagement campaign. Your product team wants to understand the drop-off between registration and first purchase.</p><p>Your data team wants to know what percentage of your user base has never touched the checkout flow.</p><p><strong>Run the query:</strong></p><pre>SELECT u.user_id, u.name, u.email<br>FROM users u<br>LEFT JOIN orders o ON u.user_id = o.user_id<br>WHERE o.order_id IS NULL;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*gtmCI_RdAgc1oG_qEUcwxA.png" /><figcaption>rows of users with no matching orders</figcaption></figure><p>These are your registered non-buyers.</p><p>LEFT JOIN keeps every row from users, even those with no matching rows in orders. For those users, every column from orders comes back NULL. The WHERE o.order_id IS NULL filter keeps only the rows where no order matched.</p><blockquote>In Parts 1–3, Eve played this role.</blockquote><blockquote>She was in the<em> </em><em>customers </em>table with no orders. She showed up in LEFT JOIN results and disappeared from INNER JOIN results.</blockquote><blockquote>In this schema, you have a realistic number of Eves.</blockquote><blockquote><strong>When she disappeared from the revenue query, that was the first signal. This query names all of them.</strong></blockquote><h4>D. Top 5 Products by Sales Quantity</h4><p><strong>The WHY</strong></p><p>You are doing quarterly inventory planning. Which products are moving the most units? Where should you prioritize restocking? Which items should you negotiate volume discounts on with your suppliers?</p><p>This query introduces order_items properly for the first time.</p><p>Product purchase history does not live in orders. It lives in order_items. Every unit of every product bought across every order has exactly one row in that table.</p><p><strong>Run the query:</strong></p><pre>SELECT p.product_id, p.name, SUM(oi.quantity) AS total_quantity_sold<br>FROM products p<br>JOIN order_items oi ON p.product_id = oi.product_id<br>GROUP BY p.product_id, p.name<br>ORDER BY total_quantity_sold DESC<br>LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*aqOtQOtjPjkuhL8dWoAIQA.png" /><figcaption>5 rows with product_id, product name, and total_quantity_sold ordered descending</figcaption></figure><p><strong>Five products. Total units sold. The top of your catalog by purchase volume.</strong></p><p>Now think about what this query excludes.</p><p>Some products in your products table will have zero rows in order_items. They are in the catalog but have never been purchased. INNER JOIN silently drops them from this result.</p><p>If you need to find those products, swap INNER JOIN for LEFT JOIN and filter on oi.order_id IS NULL. Same pattern as query C. Different table, different business question.</p><blockquote><em>One query finds your best sellers.</em></blockquote><blockquote><em>The same structure, with LEFT JOIN and a NULL filter, finds your dead stock.</em></blockquote><blockquote><strong><em>Both are inventory decisions. The SQL pattern is identical. The action that follows from each is completely different.</em></strong></blockquote><h4>E. Orders With Payment Status</h4><p><strong>The WHY</strong></p><p>Not every order has a completed payment. Orders can be placed and then abandoned before payment goes through. Payments can fail. Some orders sit in a pending state for days.</p><p>Your finance team runs this query before closing the books each month. They need to reconcile every order against its payment record and flag anything unaccounted for.</p><p><strong>Run the query:</strong></p><pre>SELECT o.order_id, o.total_amount, p.payment_status<br>FROM orders o<br>LEFT JOIN payments p ON o.order_id = p.order_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*mpCwI0I5feeFVj1Q9wVUow.png" /><figcaption>rder_id, total_amount, payment_status wiht some rows with NULL in payment_status</figcaption></figure><p>Some rows will show NULL in the payment_status column.</p><p>Those are orders with no payment record at all.</p><p>LEFT JOIN is mandatory here. INNER JOIN would silently exclude those orders, and your reconciliation report would be wrong without a single error message to tell you something was missing.</p><blockquote><em>NULL in </em><em>payment_status is not a bug in the query.</em></blockquote><blockquote><em>It is a signal from the data.</em></blockquote><blockquote><em>An order exists. A payment does not.</em></blockquote><blockquote><em>That is either an abandoned cart, a failed payment that was not recorded, or a data integrity gap worth investigating.</em></blockquote><blockquote><strong><em>The NULL is telling you something is unresolved. Do not filter it away.</em></strong></blockquote><h4>F. Users Who Spent More Than $1000</h4><p><strong>The WHY</strong></p><p>You are building a loyalty program. Gold tier requires a minimum lifetime spend of $1000. You need the exact list of users who qualify right now.</p><p>This is the same HAVING pattern from Part 3, now running against 5000 real orders instead of 10 hand-inserted rows.</p><p><strong>Run the query:</strong></p><pre>SELECT u.user_id, u.name, SUM(o.total_amount) AS total_spent<br>FROM users u<br>JOIN orders o ON u.user_id = o.user_id<br>GROUP BY u.user_id, u.name<br>HAVING SUM(o.total_amount) &gt; 1000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*8gRThNGSEhBf38575wJ94w.png" /><figcaption>showing users with total_spent above 1000</figcaption></figure><p>With 5000 orders spread across 1000 users, you will see a real distribution. Some users will be well above the threshold. Some will be just under it. The numbers are not curated. They reflect variance.</p><blockquote><em>HAVING here is not a row filter. It is a group filter.</em></blockquote><blockquote><em>By the time </em><em>HAVING runs, PostgreSQL has already computed </em><em>SUM(o.total_amount) for every user group.</em></blockquote><blockquote><em>HAVING looks at those computed totals and decides which groups survive into the result.</em></blockquote><blockquote><strong><em>You cannot do this with</em></strong><em> </em><em>WHERE</em><strong><em>, because</em></strong><em> </em><em>WHERE </em><strong><em>runs before</em></strong><em> </em><em>GROUP BY</em><strong><em>, before the totals exist. It would throw an error.</em></strong></blockquote><blockquote><strong><em>If you are not sure which one to use: if you are filtering on an aggregated value, it is</em></strong><em> </em><em>HAVING</em><strong><em>. Always.</em></strong></blockquote><h4>G. Most Recent Order Per User (CTE)</h4><p><strong>The WHY</strong></p><p>You are building a user dashboard. For each user, you want to show the date and details of their most recent order. Not a list of all their orders. Just the latest one.</p><p>This is the first time in this series we use a <strong>CTE</strong>, a Common Table Expression.</p><p>A CTE is a named subquery you define before the main query using the WITH keyword. You reference it like a table inside the main query. It does not make the query faster. It makes it readable.</p><p>A complex query broken into named CTEs is something you can understand at 9am on a Monday. The same logic crammed into a nested subquery is something you have to reverse-engineer for twenty minutes before touching.</p><p><strong>Run the query:</strong></p><pre>WITH recent_orders AS (<br>    SELECT<br>        user_id,<br>        MAX(created_at) AS latest_order_date<br>    FROM orders<br>    GROUP BY user_id<br>)<br>SELECT u.user_id, u.name, o.order_id, o.total_amount<br>FROM users u<br>JOIN orders o ON u.user_id = o.user_id<br>JOIN recent_orders ro<br>    ON o.user_id = ro.user_id<br>    AND o.created_at = ro.latest_order_date;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*sbTqCTlfrDGssfyImTtcQA.png" /><figcaption>one row per user with their most recent order_id and total_amount</figcaption></figure><p>The CTE runs first. recent_orders computes the MAX(created_at) per user, producing a temporary result set of user IDs and their latest order timestamps.</p><p>The main query then joins users to orders to recent_orders. The join condition o.created_at = ro.latest_order_date keeps only the order row that matches each user&#39;s most recent timestamp.</p><p>One row per user. The most recent order only.</p><blockquote><em>You could write this without a CTE, using a subquery in the </em><em>FROM or </em><em>WHERE clause.</em></blockquote><blockquote><em>The CTE version is not faster. It is cleaner.</em></blockquote><blockquote><em>The </em><em>WITH recent_orders AS (...) block has a name. You can read it, understand what it builds, and then read the main query knowing exactly what </em><em>recent_orders is.</em></blockquote><blockquote><strong><em>A nested subquery buried inside a larger query makes you trace it backwards. A CTE makes you read it forwards. That is the entire value.</em></strong></blockquote><h4>H. Running Total of Revenue Over Time (Window Function)</h4><p><strong>The WHY</strong></p><p>Your CFO wants a chart showing how cumulative revenue has grown over time. Not the total at the end of the quarter. The running total at each point, order by order, so you can plot the growth curve.</p><p>GROUP BY cannot do this. It collapses rows. You would get one row per time period with that period&#39;s revenue. All the individual order rows would be gone.</p><p>A <strong>window function</strong> is different.</p><p>It computes across a set of rows, but keeps every row in the result. Nothing collapses. The computation runs alongside the data, not instead of it.</p><p><strong>Run the query:</strong></p><pre>SELECT<br>    order_id,<br>    total_amount,<br>    created_at,<br>    SUM(total_amount) OVER (ORDER BY created_at) AS running_total<br>FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*9jCDSr9j8oYaXF04gtrCkA.png" /><figcaption>order_id, total_amount, created_at, and running_total with running_total visibly growing as created_at increases down the rows</figcaption></figure><p>Every order row is present in the output. A fourth column appears: running_total. For each row, it shows the sum of all total_amount values up to and including that row, ordered by created_at.</p><p>The first row shows the amount of the earliest order. The second row shows the cumulative sum of the first two. By the final row, you have the total revenue across all 5000 orders.</p><blockquote><strong><em>This is the core difference between GROUP BY and a window function.</em></strong></blockquote><blockquote><em>GROUP BY: collapse rows into one result per group. The individual rows are gone.</em></blockquote><blockquote><em>Window function: add a computed column to every existing row by looking at a defined set of surrounding rows. Nothing collapses.</em></blockquote><p>The OVER (ORDER BY created_at) part is where you define the window. You are telling PostgreSQL: for each row, compute SUM looking at all rows with a created_at value up to and including this one, in date order. Every row gets its own value for that computation.</p><blockquote><em>Window functions take a few passes to feel natural.</em></blockquote><blockquote><em>The running revenue total is the cleanest entry point: one column, one </em><em>OVER clause, a result you can immediately visualize.</em></blockquote><blockquote><strong><em>Once this one clicks, the rest of window functions become much less intimidating.</em></strong></blockquote><h3>6. Schema Design Gotchas</h3><p>The schema works. The queries run. But four decisions baked into this design look correct until they produce problems you did not see coming.</p><p>These are worth knowing before you take a schema like this to production.</p><h4>A. Snapshot Pricing in order_items</h4><p>order_items.price captures the price at the time of purchase. Not a foreign key reference. Not a dynamic lookup. A concrete number stored at that moment.</p><p>If you had stored only product_id in order_items and looked up the price from products at query time, every price update in the catalog would retroactively change historical order totals.</p><p>Your revenue reports from six months ago would produce different numbers today than when you first ran them.</p><p>That is not a query error. It is a silent wrong answer. The hardest kind to catch.</p><blockquote><strong><em>Always snapshot mutable values at transaction time. Never rely on a live reference when you need a historical record.</em></strong></blockquote><h4>B. The One-to-One Trap in payments</h4><p>The design describes orders and payments as a one-to-one relationship. Each order has one payment.</p><p>Look at the payments table definition. order_id is a foreign key into orders. But there is no UNIQUE constraint on order_id in payments.</p><p>Nothing in this schema prevents two payment rows from referencing the same order_id. The application might enforce it. The database does not.</p><p>To make the database enforce the one-to-one relationship:</p><pre>ALTER TABLE payments ADD CONSTRAINT unique_order_payment UNIQUE (order_id);</pre><blockquote><em>A relationship described in comments or documentation is not the same as a relationship enforced by a constraint.</em></blockquote><blockquote><em>Documentation drifts. A </em><em>UNIQUE constraint does not.</em></blockquote><blockquote><strong><em>Enforce at the database level what you intend to be true at the data level.</em></strong></blockquote><h4>C. status as VARCHAR Without a Constraint</h4><p>orders.status accepts any string up to 50 characters. The Python script inserts pending, completed, and cancelled. But nothing in the current schema prevents an application bug from inserting Completed, COMPLETED, shiped, or done.</p><p>Your queries filter on WHERE status = &#39;completed&#39;. If some rows say Completed and others say completed, those rows disappear from filtered results without a single error.</p><p>Two ways to fix this:</p><p><strong>Option 1: CHECK constraint</strong></p><pre>ALTER TABLE orders ADD CONSTRAINT valid_status<br>CHECK (status IN (&#39;pending&#39;, &#39;completed&#39;, &#39;cancelled&#39;));</pre><p><strong>Option 2: PostgreSQL ENUM type</strong></p><pre>CREATE TYPE order_status AS ENUM (&#39;pending&#39;, &#39;completed&#39;, &#39;cancelled&#39;);</pre><p>Then use that type for the status column instead of VARCHAR(50). Either approach makes the database reject invalid status values before they enter the table.</p><blockquote><strong><em>An invalid status value that enters the database is much harder to clean up than one the database rejected at the door.</em></strong></blockquote><h4>D. The Seed Data total_amount Mismatch</h4><p>The Python script generates total_amount on each orders row as a random number between $10 and $1000. It does not compute it from the actual order_items rows for that order.</p><p>In a real application, total_amount in orders would be the sum of quantity * price across all order_items for that order.</p><p>If you run this query to verify:</p><pre>SELECT<br>    o.order_id,<br>    o.total_amount AS stored_total,<br>    SUM(oi.quantity * oi.price) AS computed_total<br>FROM orders o<br>JOIN order_items oi ON o.order_id = oi.order_id<br>GROUP BY o.order_id, o.total_amount<br>HAVING o.total_amount &lt;&gt; SUM(oi.quantity * oi.price);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*P0_bhKBfZ7Hm98wiM3GGfQ.png" /><figcaption>verify</figcaption></figure><p>Nearly every row will show a mismatch. This is a seed data simplification, not a schema flaw.</p><blockquote><em>Do not let seed data shortcuts shape how you think the production system should work.</em></blockquote><blockquote><em>In production, you would either compute </em><em>total_amount dynamically at query time, or recalculate and update it every time an </em><em>order_items row is added, changed, or removed.</em></blockquote><blockquote><strong><em>The schema is correct. The script took a shortcut. Know the d</em>ifference.</strong></blockquote><h3>7. Conclusion</h3><p>You have a schema now that could back a real application.</p><p>not just a flat table with a text column for product names.</p><p><strong>A five-table relational design with</strong></p><ul><li>foreign keys that reject orphaned data</li><li>unique constraints that prevent duplicate transactions, and</li><li>a junction table that correctly models the relationship between orders and the products inside them.</li></ul><p><strong>The 8 queries covered a range of patterns:</strong></p><ul><li>basic JOINs</li><li>GROUP BY with aggregation</li><li>LEFT JOIN with NULL filtering</li><li>HAVING on grouped results</li><li>a CTE, and</li><li>a window function.</li></ul><p>Two of those, the CTE and the window function, appear in this series for the first time.</p><p>But the most important thing in this part was not any individual query.</p><blockquote><em>A good schema makes queries simple.</em></blockquote><blockquote><em>A bad schema turns queries into workarounds.</em></blockquote><blockquote><strong><em>Design the data model before you write a single line of SQL.</em></strong></blockquote><blockquote><strong><em>The queries follow from it.</em></strong></blockquote><blockquote>Part 5 takes this schema off your local machine.</blockquote><p><strong>We provision a PostgreSQL instance on AWS RDS using Pulumi,</strong> configure security groups so the database is accessible without being open to the world, and end up with a production-ready PostgreSQL endpoint instead of a local psql session. Everything you built and seeded here gets a real sync.</p><h3>8. Resources</h3><ul><li><strong>PostgreSQL Foreign Keys Documentation:</strong> Complete reference for defining and managing foreign key constraints. <a href="https://www.postgresql.org/docs/current/ddl-constraints.html">postgresql.org/docs/current/ddl-constraints.html</a></li><li><strong>PostgreSQL Window Functions Documentation:</strong> Full guide to OVER, PARTITION BY, and all window function syntax. <a href="https://www.postgresql.org/docs/current/functions-window.html">postgresql.org/docs/current/functions-window.html</a></li><li><strong>PostgreSQL CTEs Documentation:</strong> How CTEs work, when to use them, and the recursive CTE syntax. <a href="https://www.postgresql.org/docs/current/queries-with.html">postgresql.org/docs/current/queries-with.html</a></li><li><strong>Faker Library Documentation:</strong> Everything you can generate with Python Faker for realistic test data. <a href="https://faker.readthedocs.io/">faker.readthedocs.io</a></li><li><strong>Part 3 of this series:</strong> Aggregations, GROUP BY, HAVING, and the query execution order that makes all of it make sense. <a href="https://imehboob.medium.com/aggregations-grouping-in-sql-the-queries-behind-every-dashboard-and-report-part-3-9bd1ce9bd6a0">Part 3</a></li></ul><h3>9. Next Part</h3><p><strong>Part 5 is about taking PostgreSQL to AWS.</strong></p><p>We spin up a PostgreSQL instance on RDS using <strong>Pulumi</strong>, which is Infrastructure as Code in Python. You define the instance, the security groups, and the networking rules in code, and Pulumi provisions all of it on AWS in a single command.</p><p>The ecommerce schema you built in this part comes with us. Same tables. Same structure. Different address. If you have never used Pulumi or provisioned any cloud infrastructure with code before, <strong>Part 5 starts from zero. no prior IaC experience needed.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27f6f6979917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aggregations & Grouping in SQL: The Queries Behind Every Dashboard and Report | Part 3]]></title>
            <link>https://imehboob.medium.com/aggregations-grouping-in-sql-the-queries-behind-every-dashboard-and-report-part-3-9bd1ce9bd6a0?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bd1ce9bd6a0</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Wed, 13 May 2026 15:09:03 GMT</pubDate>
            <atom:updated>2026-05-13T15:10:43.783Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdLH-Czj_eX-5jJ1El2ASw.png" /><figcaption>image credit: grok</figcaption></figure><h3>Table of Contents</h3><ul><li><strong>Quick Recap of Part 2</strong></li><li><strong>Who This Is For</strong></li><li><strong>What You Will Have Built by the End of Part 3</strong></li></ul><ol><li><strong>Why Aggregations Exist</strong></li><li><strong>Extending the Schema for Part 3</strong></li><li><strong>The 5 Aggregate Functions</strong></li></ol><ul><li><strong>A. SUM — What Is the Total</strong></li><li><strong>B. COUNT — How Many</strong></li><li><strong>C. AVG — What Is Typical</strong></li><li><strong>D. MAX and MIN — What Are the Extremes</strong></li></ul><p><strong>4. GROUP BY: From One Number to a Breakdown</strong></p><ul><li><strong>A. Total Spend Per Customer</strong></li><li><strong>B. Total Orders Per Customer</strong></li><li><strong>C. Orders Per Day</strong></li><li><strong>D. JOIN + GROUP BY: Names Instead of IDs</strong></li></ul><p><strong>5. HAVING: Filtering After You Group</strong></p><ul><li><strong>A. Customers Who Spent More Than $500</strong></li><li><strong>B. Order Dates With More Than One Order</strong></li><li><strong>C. Customers Who Placed More Than 2 Orders</strong></li></ul><p><strong>6. Watch-outs, Gotchas, and Best Practices</strong></p><ul><li><strong>A. WHERE vs HAVING: the confusion that breaks real queries</strong></li><li><strong>B. COUNT(*) vs COUNT(column): they are not the same</strong></li><li><strong>C. NULLs inside AVG and SUM</strong></li><li><strong>D. The column-not-in-GROUP-BY error</strong></li><li><strong>E. Query Execution Order</strong></li></ul><p><strong>7. Conclusion</strong></p><p><strong>8. Resources</strong></p><p><strong>9. Next Part</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FHHYtj%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FHHYtj%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FHHYtj%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="1905" frameborder="0" scrolling="no"><a href="https://medium.com/media/55d3c1ae9cf6ee3ae0a3fc883b4f585d/href">https://medium.com/media/55d3c1ae9cf6ee3ae0a3fc883b4f585d/href</a></iframe><h3>Quick Recap of Part 2</h3><p><strong>In Part 2, we</strong></p><ul><li>dropped the old orders table from Part 1 and rebuilt the schema with a richer customers and orders table</li><li>ran all 5 JOIN types hands-on and watched the output change based on which rows had no match on either side</li><li>understood NULLs not as errors but as signals about the state of your data</li><li>combined JOINs with WHERE and ORDER BY for real query patterns</li><li>ended Part 2 with a teaser query using SUM and GROUP BY that we promised to explain properly</li></ul><p><strong>If you have not done Part 2 yet, start there first:</strong> <a href="https://imehboob.medium.com/sql-joins-in-postgresql-query-across-multiple-tables-and-actually-understand-what-you-are-asking-6b4dec98cd5c"><strong>Part 2: SQL JOINs in PostgreSQL</strong></a>.</p><p>In this part, we pick up exactly where we left off.</p><p>Same customers and orders tables.</p><p>Same testuser and testdb.</p><p>We add more rows to make the aggregation results meaningful, and then we go throught every tool behind the kind of query</p><ul><li>your manager</li><li>your product team, and</li><li>your dashboards</li></ul><p>are always waiting on.</p><h3>Who This Is For</h3><p>This part is tagged <strong>[Beginner]</strong>.</p><p>You need Part 2 complete. testuser, testdb, and the customers and orders tables should all exist.</p><p>If you are continuing from the same terminal session, you are already in. If you are picking this up fresh, log in first.</p><p><strong>Log in to psql as testuser</strong></p><pre>psql -U testuser -d testdb</pre><p>That is all you need to continue.</p><h3>What You Will Have Built by the End of Part 3</h3><p><strong>By the time you close this tab, you will have</strong></p><ul><li>Extended the orders table with 5 new rows so the grouping results are actually meaningful</li><li>Used all 5 aggregate functions (SUM, COUNT, AVG, MAX, MIN) against real data and understood what business question each one is answering</li><li>Used GROUP BY to break full-table summaries down into per-customer and per-date breakdowns</li><li>Filtered grouped results with HAVING to answer questions like &quot;<em>who spent more than $500 total</em>&quot; and &quot;<em>which days had more than one order</em>&quot;</li><li>Combined JOINs with GROUP BY to get customer names alongside their spend totals</li><li>known exactly when WHERE applies and when HAVING applies, and why that distinction breaks real production queries when you get it wrong</li></ul><p>okey, so let’s start.</p><h3>1. Why Aggregations Exist, Anyway</h3><p>Well, your manager sends a message on Monday morning.</p><blockquote><em>Can you pull total revenue for last week?</em></blockquote><blockquote><em>Also which customers are spending the most?</em></blockquote><p>You open psql. You run SELECT * FROM orders. You get 10 rows back.</p><p>Amounts.</p><p>Products.</p><p>Dates.</p><p><strong>The data is all there. The answer is not.</strong></p><p>You cannot read a column of 10 numbers and instantly know the total.</p><p>You cannot scan rows and know which customer spent the most without doing math.</p><p>The database has the raw facts. You need it to compute something from those facts.</p><p>That is aggregation.</p><p>It takes a column of values and collapses them into a number that means something.</p><p>A total.</p><p>A count.</p><p>An average.</p><p>The highest value.</p><p>The lowest.</p><p>And this is not a niche thing.</p><p>Every engineering team ships something that answers one of these questions.</p><p>The analytics page in your app.</p><p>The revenue chart in the admin panel.</p><p>The user growth graph. The billing summary. The downtime report.</p><p><strong>All of it is aggregation.</strong></p><p>not complicated aggregation.</p><p>Usually just five functions.</p><blockquote>But the engineers who understand them deeply,</blockquote><blockquote>who know when to group, when to filter before grouping, when to filter after,</blockquote><blockquote>are the ones who write those queries in five minutes instead of thirty</blockquote><h4>A. What Aggregation Is Actually Doing</h4><p>Just think of it like a bank passbook. think simple.</p><p>Your passbook has one row per transaction.</p><p>Every credit, every debit, every transfer.</p><p>If your bank handed you the raw passbook and said “tell me your balance,” you would have to add and subtract every row manually.</p><blockquote><em>What the bank actually shows you is the aggregated result.</em></blockquote><blockquote><em>One number. Your current balance. Computed from all those rows.</em></blockquote><blockquote><em>SQL aggregation is the same operation. You have rows. You want the number those rows produce.</em></blockquote><p>The functions do the arithmetic.</p><p>yiou just need to tell them which column to compute on, and in some cases, which groups to compute it for separately.</p><h3>2. Extending the Schema for Part 3</h3><p>The orders table from Part 2 has 5 rows. Alice, Bob, and Charlie each have a couple of orders.</p><p>Five rows is not enough to make grouping patterns visible. When you GROUP BY customer_id on five rows, you get three groups with one or two rows each. The numbers are too close together to tell a story.</p><p>We extend to 10 orders. More spread across customers and dates.</p><p><strong>Check what is currently in orders</strong></p><pre>SELECT * FROM orders;</pre><p>You should see 5 rows: <strong>Laptop, Mouse, Keyboard, Monitor, Tablet.</strong></p><p><strong>Insert 5 more orders:</strong></p><pre>INSERT INTO orders (customer_id, product, amount, order_date) VALUES<br>(1, &#39;Speaker&#39;, 50.00, &#39;2024-07-03&#39;),<br>(2, &#39;Headphones&#39;, 100.00, &#39;2024-07-04&#39;),<br>(2, &#39;Mousepad&#39;, 15.00, &#39;2024-07-05&#39;),<br>(3, &#39;Webcam&#39;, 80.00, &#39;2024-07-05&#39;),<br>(1, &#39;Smartphone&#39;, 800.00, &#39;2024-07-06&#39;);</pre><p><strong>Verify the full table:</strong></p><pre>SELECT * FROM orders ORDER BY order_date;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*1u7PekKaqzGztAh6YXE_ew.png" /><figcaption>10 orders in orders table</figcaption></figure><p>You now have 10 orders spanning 6 days. Here is what the data looks like per customer:</p><ul><li><strong>Alice (customer_id 1):</strong> Laptop $1200, Mouse $25, Speaker $50, Smartphone $800. Four orders. $2075 total.</li><li><strong>Bob (customer_id 2):</strong> Keyboard $75, Headphones $100, Mousepad $15. Three orders. $190 total.</li><li><strong>Charlie (customer_id 3):</strong> Monitor $300, Tablet $600, Webcam $80. Three orders. $980 total.</li><li><strong>Eve (customer_id 4):</strong> No orders at all.</li></ul><p>The spread matters here.</p><p>Alice is a high-value customer.</p><p>Bob is a frequent buyer at low amounts.</p><p>Charlie is somewhere in between.</p><p>Eve has registered but never bought anything.</p><p>These differences will make each query tell a different story about the same data.</p><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote><em>Eve was added in Part 2 to demonstrate LEFT JOIN.</em></blockquote><blockquote><em>She still exists in </em><em>customers with no orders. She will show up, or not show up, at key moments in this part.</em></blockquote><blockquote><strong><em>When she disappears from a result, that disappearance is itself information.</em></strong></blockquote><h3>3. The 5 Aggregate Functions</h3><p>Aggregate functions collapse many rows into one number.</p><p>Run them against the whole table and you get one row back. That single number summarizes everything in that column.</p><p><strong>Here are the five functions you need</strong></p><p>SUM() <strong>Total of all values in a column</strong></p><p>COUNT() <strong>Number of rows</strong></p><p>AVG()<strong> Average of all values</strong></p><p>MAX() <strong>Largest value</strong></p><p>MIN() <strong>Smallest value</strong></p><p>Let us go through each one, not as functions to memorize, but as answers to real questions.</p><h4>A. SUM — What Is the Total</h4><p><strong>The WHY</strong></p><p>The most common question in any data-driven business is</p><ul><li><strong>how much?</strong></li><li><strong>How much revenue?</strong></li><li><strong>How much was spent?</strong></li><li><strong>How much did this customer order?</strong></li></ul><p>SUM answers that.</p><p>Your finance team is closing the books for July.</p><p><strong>They need one number</strong></p><ul><li><strong>total revenue from all orders.</strong></li></ul><p>Not a list of individual amounts. <strong>The Total.</strong></p><p><strong>Run the query:</strong></p><pre>SELECT SUM(amount) AS total_revenue FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*lSXnhHlkMAxqzNwupxBk7g.png" /><figcaption>SUM aggregatoin on orders table</figcaption></figure><p><strong>$3245.00. Every order in the table added together. One row. One answer.</strong></p><blockquote><strong><em>Now here is another situation where the same function solves a completely different problem.</em></strong></blockquote><p>Imagine you are not looking at orders.</p><p>You are looking at a cloud billing table.</p><p><strong>Each row is a resource charge</strong></p><ul><li><strong>one EC2 instance</strong></li><li><strong>one S3 bucket</strong></li><li><strong>one RDS snapshot.</strong></li></ul><p><strong>Your month-end invoice is the sum of all those rows.</strong></p><p>SELECT SUM(cost) FROM aws_billing WHERE month = &#39;2024-07&#39; gives you what you owe before the bill arrives.</p><p>Same function.</p><p>Completely different context.</p><p><strong>The problem was &quot;how much is this costing us&quot; and SQL gave you the answer in one query.</strong></p><p><strong>SUM does not care what you are adding.</strong></p><p><strong>Revenue, costs, weights, durations.</strong></p><p><strong>If it is a number and you need the total, SUM is the answer.</strong></p><h4>B. COUNT — How Many</h4><p><strong>The WHY</strong></p><p>Sometimes the question is not about value.</p><p><strong>It is about volume</strong></p><ul><li><strong>How many orders came in?</strong></li><li><strong>How many users signed up?</strong></li><li><strong>How many records match this condition?</strong></li></ul><p><strong>COUNT answers that.</strong></p><p>So, your ops team is reviewing Monday’s activity.</p><blockquote><em>They do not care about revenue right now</em></blockquote><blockquote><em>They want to know how much traffic the system handled</em></blockquote><blockquote><em>How many orders were processed</em></blockquote><p><strong>Run the query:</strong></p><pre>SELECT COUNT(order_id) AS total_orders FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*-DVd4b7JnYkkkCz6jAZ5pA.png" /><figcaption>COUNT output on testdb orders table</figcaption></figure><p><strong>10 orders. That is the volume.</strong></p><blockquote><em>But COUNT is not just for measuring normal traffic.</em></blockquote><blockquote><em>It shows up in debugging too, more than people expect.</em></blockquote><p><strong>Say you are getting a complaint</strong></p><ul><li>this customer appears twice in the system.</li></ul><p><strong>Before chasing it through the application layer, you run a quick count</strong></p><pre>SELECT customer_name, COUNT(*) AS appearances<br>FROM customers<br>GROUP BY customer_name<br>HAVING COUNT(*) &gt; 1;</pre><p>If that query returns rows, you have duplicates.</p><p>If it returns nothing, the data is clean.</p><p>You just saved yourself twenty minutes of debugging by running a two-second query.</p><p>The pattern is the same. You had a question about existence and count.</p><p>SQL answered it before you could even open the application logs.</p><p><strong>COUNT is the first thing you run when you need to understand the size of a problem. Not the last.</strong></p><h4>C. AVG — What Is Typical</h4><p><strong>The WHY</strong></p><p>Today your product team is designing a promotional offer.</p><blockquote><em>Spend $200 and get 20% off your next order.</em></blockquote><p><strong>Before they ship that campaign, someone should check</strong></p><ul><li><strong>is $200 a reasonable threshold?</strong></li><li><strong>is that above or below what a typical customer already spends per order?</strong></li><li><strong>if the average order is $30, the threshold is so far above typical behavior that almost nobody qualifies.</strong></li></ul><blockquote>The campaign is dead before it launches</blockquote><p><strong>Run the query:</strong></p><pre>SELECT AVG(amount) AS avg_order_value FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*wuK7So71t4DWGrpzUP6Kfw.png" /><figcaption>AVG outptu on orders table</figcaption></figure><p><strong>$324.50. The average order across all 10 transactions.</strong></p><blockquote><em>That number should give you pause.</em></blockquote><blockquote><em>$324 average, but 5 of your 10 orders are under $100. How is the average that high?</em></blockquote><p>Alice’s Laptop ($1200) and Smartphone ($800) are pulling it up.</p><p>Two large orders are skewing the average well above what most customers spend in reality.</p><blockquote><strong><em>This is the classic trap with averages. They are accurate. They are also misleading when the data is uneven.</em></strong></blockquote><p>Here is another place where the same thinking applies.</p><p>A support team tracking ticket resolution time runs AVG(resolution_hours) to measure how fast they close issues.</p><p>They get 4.2 hours. Management celebrates. But three urgent tickets took 30 hours each because of an escalation issue, and they are dragging the average up. The 200 routine tickets closed in under an hour are masked by those three outliers.</p><blockquote>AVG is a starting point, not a conclusion</blockquote><blockquote>Always follow it with MAX and MIN to understand the range around that average</blockquote><h4>D. MAX and MIN — What Are the Extremes</h4><p><strong>The WHY</strong></p><p>MAX and MIN are almost always used together. They tell you the range.</p><p>Your finance team wants to flag any unusually large order for manual review before processing.</p><p>Your inventory team wants to know the cheapest product to understand where the low-end of the catalog is.</p><p><strong>Run both at once:</strong></p><pre>SELECT MAX(amount) AS highest_order, MIN(amount) AS lowest_order FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*lPperK6AFWLhvt9-WRP6Tw.png" /><figcaption>output of MIN and MAX 0n orders table</figcaption></figure><p><strong>Highest: $1200 (the Laptop). Lowest: $15 (the Mousepad).</strong></p><p><strong>Now go back to the average we computed: $324.50.</strong></p><p>Your data spans from $15 to $1200.</p><p>The average of $324 sits in the upper third of that range.</p><blockquote>If you design a campaign assuming $324 is typical, you are designing for the minority of your customers, not the majority</blockquote><p>MAX and MIN give you the context that makes AVG honest.</p><p>There is another use case worth calling out.</p><p>Say you have a last_login column on a users table.</p><p>MIN(last_login) tells you when the oldest inactive user last appeared.</p><p>MAX(last_login) tells you the most recent login across the whole system.</p><blockquote><em>Both are signals.</em></blockquote><blockquote><em>The first helps you find churned users for a re-engagement campaign</em></blockquote><blockquote><em>The second tells you your platform is alive and being used today.</em></blockquote><blockquote><em>Same function. Very different business questions.</em></blockquote><p><strong>MAX and MIN are the sanity check for every average you compute, and independwent signals in their own right.</strong></p><h3>4. GROUP BY: From One Number to a Breakdown</h3><p><strong>So far, every query returned one row.</strong></p><p><strong>Total reveneue: one number.</strong></p><p><strong>Total orders: one number.</strong></p><p><strong>Average order value: one number.</strong></p><p>That is useful for a top-line summary.</p><p><strong>But your product team does not just want total revenue.</strong></p><ul><li>They want total revenue per customer.</li></ul><p><strong>Your ops team does not want total orders.</strong></p><ul><li>They want total orders per day.</li></ul><p>The CFO wants the breakdown by category, not the single aggregate.</p><blockquote><strong>One number is a summary. A breakdown is an insight.</strong></blockquote><p>GROUP BY is how you go from one to the other. It splits the table into groups based on a column, then runs the aggregate function separately on each group.</p><p>Instead of summing all 10 rows into one number, it sums the rows for Alice, then the rows for Bob, then the rows for Charlie. You get three numbers back, one per group.</p><h4>A. Total Spend Per Customer</h4><p><strong>The WHY</strong></p><p>You are building a customer leaderboard.</p><p>Not a list of orders.</p><p>A list of customers ranked by how much they have spent in total.</p><p>This is one of the most common queries you will write in production</p><ul><li>E-commerce dashboards.</li><li>SaaS billing reports</li><li>Loyalty programs</li></ul><blockquote><em>Every system that has customers and transactions eventually needs to answer this: </em><strong><em>who is spending the most?</em></strong></blockquote><p><strong>Run the query:</strong></p><pre>SELECT customer_id, SUM(amount) AS total_spent<br>FROM orders<br>GROUP BY customer_id<br>ORDER BY total_spent DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*Os8nO9kEMrHocqiZZGoyfA.png" /><figcaption>GROUP BY output</figcaption></figure><p><strong>Three rows. One per customer who has orders.</strong></p><p>Alice ($2075) is your top customer by a wide margin. Charlie ($980) is second. Bob ($190) is third.</p><p><strong>Now you can act on this.</strong></p><blockquote><em>Alice gets the VIP email.</em></blockquote><blockquote><em>Charlie goes into the high-engagement bucket.</em></blockquote><blockquote><em>Bob is a candidate for an upsell campaign since he orders often but at low amounts.</em></blockquote><p>Notice that Eve is not in this result. She has no orders, so there are no rows for her to group. GROUP BY can only group rows that exist.</p><p>If you need Eve to appear with a $0 total, you would use a LEFT JOIN from customers into orders before aggregating, the same LEFT JOIN pattern from <a href="https://imehboob.medium.com/sql-joins-in-postgresql-query-across-multiple-tables-and-actually-understand-what-you-are-asking-6b4dec98cd5c">Part 2.</a></p><p>Let me give you another angle on this same result.</p><p><strong>What if your product team wants to know which customers to prioritize for a premium support tier?</strong></p><p>$500 might be the threshold. Anyone above it gets dedicated support. You now know Alice and Charlie qualify. You can build that segment from a single query.</p><p><strong>The query did not change. The business decision behind it did.</strong></p><h4>B. Total Orders Per Customer</h4><p><strong>The WHY</strong></p><p>Spend and order volume tell different stories.</p><p>A customer who places 10 orders at $10 each looks very different from a customer who places 1 order at $100.</p><blockquote>The revenue is the same. The behavior is completely different</blockquote><blockquote>Your retention team cares about behavior</blockquote><blockquote>Frequent orders mean habit.</blockquote><blockquote>Habit means retention.</blockquote><blockquote>One big order might just be a one-time purchase.</blockquote><p><strong>Run the query:</strong></p><pre>SELECT customer_id, COUNT(order_id) AS total_orders<br>FROM orders<br>GROUP BY customer_id<br>ORDER BY total_orders DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*5ysnxSjEFguji9ah-V1pRQ.png" /><figcaption>order count per customer</figcaption></figure><p>Alice has 4 orders. Bob and Charlie each have 3.</p><blockquote><em>Now cross-reference with the spend query.</em></blockquote><blockquote><em>Alice has the most orders AND the most spend.</em></blockquote><blockquote><em>She is your best customer by every metric.</em></blockquote><p>Bob has 3 orders at only $190 total. His average order is about $63. He is an engaged buyer, but at low price points.</p><p>An upsell campaign targeting Bob makes sense because he clearly has the purchasing habit, he just has not bought high-value items yet.</p><p>Charlie has 3 orders at $980 total. His average order is about $327. He buys infrequently but spends big when he does.</p><blockquote><em>The strategy for Charlie is different from the strategy for Bob. For Charlie, you want to shorten the gap between purchases</em></blockquote><blockquote><strong>Three customers</strong></blockquote><blockquote><strong>Three profiles</strong></blockquote><blockquote><strong>Three different actions</strong></blockquote><blockquote><strong>One GROUP BY query on each metric made all of that visible.</strong></blockquote><h4>C. Orders Per Day</h4><p><strong>The WHY</strong></p><p><strong>Understanding when your customers buy is as important as understanding who buys</strong></p><ul><li>Your infrastructure team needs to know peak traffic windows to right-size auto-scaling policies.</li><li>Your marketing team wants to know which campaign dates drove the most order volume</li><li>Your support team wants to understand when they need extra staffing</li></ul><p><strong>All three of those problems reduce to the same question</strong></p><ul><li><strong>how many orders happened on each day?</strong></li></ul><p><strong>Run the query:</strong></p><pre>SELECT order_date, COUNT(order_id) AS orders_per_day<br>FROM orders<br>GROUP BY order_date<br>ORDER BY order_date;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*njq4ebLiEjr_OjiNCbMTYw.png" /><figcaption>orders per date in orders table</figcaption></figure><p>Some days have one order.</p><p>Some have two.</p><p>July 2rd through 5th are the busiest days in this dataset.</p><p>Now think about what this query becomes in a real system.</p><p>You have 90 days of order data. You run this query.</p><p>You see a spike every Friday. That spike is not random. Maybe you send a promotional email every Thursday night.</p><p>Maybe your customers get paid on Fridays. Maybe a competitor runs sales on weekends and your users check them first.</p><p><strong>The query just shows you the pattern. Understanding why the pattern exists is where engineering and business knowledge have to meet.</strong></p><p>And the same pattern works across different problems.</p><p>Your DevOps team has an incidents table.</p><p>GROUP BY incident_date and COUNT(incident_id) tells them which days had the most failures.</p><p>Your sales team has a deals table. Same query tells them which days they closed the most deals.</p><p><strong>The function and the group key stay the same. The table and the business question change.</strong></p><h4>D. JOIN + GROUP BY: Names Instead of IDs</h4><p><strong>The WHY</strong></p><p>Customer IDs are useful in code. They mean nothing to a product manager, a finance director, or anyone outside of engineering.</p><p>When you present data to a human, you present names.</p><p>But names live in the customers table. Revenue lives in the orders table.</p><p>To get both in one result, you join first, then aggregate on the joined output.</p><p>This is the full query that was teased at the end of Part 2. Here is what every part of it does.</p><p><strong>Run the query:</strong></p><pre>SELECT c.customer_name, SUM(o.amount) AS total_spent<br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id<br>GROUP BY c.customer_name<br>ORDER BY total_spent DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*tqx9iLi_r6hgUmNyX7BCUQ.png" /><figcaption>customer with total spends</figcaption></figure><p>Three rows. Ordered by total spend. Names instead of IDs.</p><blockquote>This is the query you send to your product manager in a CSV</blockquote><blockquote>Not the customer_id version</blockquote><blockquote>This one</blockquote><p><strong>The execution order here matters.</strong></p><ul><li>The INNER JOIN runs first and builds a combined table of customers and their orders.</li><li>GROUP BY c.customer_name then splits that combined table into groups, one per name.</li><li>SUM(o.amount) runs on each group separately.</li><li>ORDER BY total_spent DESC sorts the final grouped result.</li></ul><p><strong>Four steps. Each builds on the previous one.</strong></p><blockquote><em>Notice Eve is still missing.</em></blockquote><p>INNER JOIN excluded her because she has no matching rows in orders.</p><p>If you want Eve to appear with a total of $0 or NULL, swap INNER JOIN for LEFT JOIN.</p><p>The rest of the query stays identical. You get four rows instead of three, and Eve shows up with NULL for total_spent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*onYXy7MEgVG-9pFdsHsClw.png" /><figcaption>same query with left join</figcaption></figure><p><strong>The JOIN type controls which rows enter the aggregation.</strong></p><p><strong>Change the JOIN, change the population of customers you are computing over.</strong></p><h3>5. HAVING: Filtering After You Group</h3><blockquote><em>WHERE filters rows before grouping happens.</em></blockquote><blockquote><em>HAVING filters groups after grouping has already happened.</em></blockquote><blockquote>this is not a subtle difference.</blockquote><blockquote>it breaks real queries when you get it wrong.</blockquote><p><strong>The reason is execution order</strong></p><ul><li>When WHERE runs, the database has not yet grouped anything. The aggregated values, SUM(amount), COUNT(order_id), none of them exist yet. WHERE cannot see them.</li><li>By the time HAVING runs, grouping is done. The aggregated values are computed. HAVING can filter on them.</li></ul><blockquote><strong>WHERE for rows. HAVING for groups. Never mix them up.</strong></blockquote><h4>A. Customers Who Spent More Than $500</h4><p><strong>The WHY</strong></p><p>SO, again you are setting up a tiered loyalty program.</p><ul><li>Bronze</li><li>silver</li><li>gold</li></ul><p><strong>Gold tier requires a minimum lifetime spend of $500</strong></p><p>You need the list of customers who qualify.</p><blockquote><strong><em>A WHERE clause cannot help you here.</em></strong></blockquote><blockquote><strong><em>You need the total spend per customer first, then filter on that total.</em></strong></blockquote><blockquote><strong><em>That is two steps. GROUP BY does the first. HAVING does the second.</em></strong></blockquote><p><strong>Run the query:</strong></p><pre>SELECT customer_id, SUM(amount) AS total_spent<br>FROM orders<br>GROUP BY customer_id<br>HAVING SUM(amount) &gt; 500;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*KdwuL52aXulel7kbcsLwfg.png" /><figcaption>having filter result</figcaption></figure><p><strong>Two rows. Alice and Charlie qualify. Bob’s $190 does not make the cutoff.</strong></p><blockquote>One thing to watch: SUM(amount) &gt; 500 is written in the HAVING clause, not the alias total_spent</blockquote><blockquote>You cannot use the alias in HAVING because the alias is defined in SELECT, which runs after HAVING in the execution order. Write the full expression in HAVING</blockquote><p>Now let me give you another angle on the same pattern.</p><p>Same query, different threshold.</p><p>Your finance team wants to flag any customer whose total spend exceeds $1000 for a personalized account manager call.</p><p>Change &gt; 500 to &gt; 1000.</p><pre>SELECT customer_id, SUM(amount) AS total_spent<br>FROM orders<br>GROUP BY customer_id<br>HAVING SUM(amount) &gt; 1000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Ke2w0KpdDBb2S4pphfvqOA.png" /><figcaption>same query with larger amount threshold</figcaption></figure><p>Only Alice remains. She spent $2075. Charlie’s $980 now falls below the threshold.</p><blockquote><strong><em>The GROUP BY logic did not change. The business threshold did. HAVING makes that threshold a runtime parameter, not a hardcoded filter.</em></strong></blockquote><h4>B. Order Dates With More Than One Order</h4><p><strong>The WHY</strong></p><p>Your platform had a brief performance degradation on certain days last week.</p><p>Before escalating, your team wants to know which days actually had concurrent activity.</p><p><strong>A single order on a given day is not a load problem. Multiple orders on the same day might be.</strong></p><p><strong>Run the query:</strong></p><pre>SELECT order_date, COUNT(order_id) AS orders_per_day<br>FROM orders<br>GROUP BY order_date<br>HAVING COUNT(order_id) &gt; 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*oOchEQNuLTk3L1qeoetJKA.png" /><figcaption>orders with dates</figcaption></figure><p>July 2nd, 3rd, 4th, and 5th each had 2 orders. The other days had only 1.</p><p>Your infrastructure team now knows which dates had concurrent load. If they need to correlate this with slow query logs or CPU spikes, they have the exact dates to look up.</p><p>And the same pattern transfers across completely different contexts.</p><p>Say your company has a sales table with a sales_rep_id and deal_date.</p><p>Your sales manager wants to know which reps closed more than 3 deals in a single day this quarter.</p><p>GROUP BY sales_rep_id, deal_date HAVING COUNT(deal_id) &gt; 3 answers that in one query.</p><p><strong>Same structure. Different table. Different business question.</strong></p><blockquote><strong><em>HAVING is just a threshold applied to a group. The group can be anything. The threshold can be anything.</em></strong></blockquote><h4>C. Customers Who Placed More Than 2 Orders</h4><p><strong>The WHY</strong></p><blockquote><em>High-frequency buyers and high-value buyers are not the same thing.</em></blockquote><blockquote><em>You already saw this with Bob. He orders often but spends little per order.</em></blockquote><p>Your retention team wants to identify customers who have demonstrated purchasing habit, regardless of order size.</p><p>More than 2 orders is their threshold for “<strong>this person is actually using the platform, not just experimenting once.</strong>”</p><p><strong>Run the query:</strong></p><pre>SELECT customer_id, COUNT(order_id) AS order_count<br>FROM orders<br>GROUP BY customer_id<br>HAVING COUNT(order_id) &gt; 2;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*S1jXX_-wWRt0quMORDa-iA.png" /><figcaption>all three customers qualify</figcaption></figure><p>All three active customers qualify. Change the threshold to &gt; 3 and only Alice remains, with her 4 orders.</p><p>Your retention team can now build their cohort.</p><p><strong>Every customer with more than 2 orders gets tagged as “habitual buyer” in the CRM.</strong></p><p><strong>Their communication strategy for this group is different: they focus on cross-sell and loyalty, not re-engagement.</strong></p><blockquote><strong><em>The cohort came from HAVING. The business strategy follows from it.</em></strong></blockquote><h3>6. Watch-outs, Gotchas, and Best Practices</h3><p>The functions above are not complicated. But they produce silently wrong results in specific situations that are easy to hit without realizing it.</p><p>These are the mistakes worth knowing before you encounter them in production.</p><h4>A. WHERE vs HAVING: the confusion that breaks real queries</h4><p>You already know the difference conceptually. Here is what it looks like when you get it wrong.</p><p><strong>This will fail:</strong></p><pre>-- it is wrong: WHERE cannot see the aggregated value<br><br>SELECT customer_id, SUM(amount) AS total_spent<br>FROM orders<br>WHERE SUM(amount) &gt; 500<br>GROUP BY customer_id;</pre><pre>ERROR: aggregate functions are not allowed in WHERE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*7iEUlqwWZbDy7MQujM4gXg.png" /><figcaption>ERROR in aggregate function</figcaption></figure><p><strong>PostgreSQL rejects it immediately. Good. You know where the problem is.</strong></p><p><strong>This is correct:</strong></p><pre>SELECT customer_id, SUM(amount) AS total_spent<br>FROM orders<br>WHERE order_date &gt;= &#39;2024-07-03&#39;<br>GROUP BY customer_id<br>HAVING SUM(amount) &gt; 500;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*b24Te9kop03YIe8KI3KYnw.png" /><figcaption>correct output as expected</figcaption></figure><p>WHERE filters which rows enter the grouping step. Only orders from July 3rd onward get grouped.</p><p>HAVING filters which groups appear in the result. Only groups with a total above $500 survive.</p><blockquote><strong><em>Both can live in the same query. They just operate at completely different stages of execution.</em></strong></blockquote><h4>B. COUNT(*) vs COUNT(column): they are not the same</h4><p>COUNT(*) counts all rows in the group, including rows where columns might be NULL.</p><p>COUNT(column) counts only rows where that specific column is not NULL.</p><pre>SELECT COUNT(*) FROM orders;        -- counts every row: 10<br>SELECT COUNT(order_id) FROM orders; -- counts non-null order_id values: also 10 here</pre><p>for a NOT NULL primary key like order_id, both return the same thing.</p><p>The difference surfaces on nullable columns.</p><p>say your orders table had an optional coupon_code column.</p><p>Some orders used a coupon.</p><p>Most did not.</p><p>COUNT(coupon_code) tells you exactly how many orders had a coupon applied. COUNT(*) tells you total orders. The ratio between those two numbers is your coupon adoption rate.</p><blockquote><strong><em>Use </em></strong><strong><em>COUNT(*) when you want row count.</em></strong></blockquote><blockquote><strong><em>Use </em></strong><strong><em>COUNT(column) when you want to count non-null occurrences of a specific field</em></strong></blockquote><blockquote><strong><em>They are different questions</em></strong></blockquote><h4>C. NULLs inside AVG and SUM</h4><p>AVG ignores NULL values. It does not treat them as zero.</p><p><strong>say you have 5 rows with amounts</strong></p><ul><li>100</li><li>200</li><li>NULL</li><li>400</li><li>NULL</li></ul><blockquote>AVG(amount) returns 233.33, not 140.</blockquote><blockquote>It adds 100 + 200 + 400 and divides by 3, not 5.</blockquote><blockquote>The two NULLs are excluded from both the numerator and the denominator.</blockquote><p>that is usually what you want. An order where the amount is not yet recorded should not drag down the average.</p><p>but sometimes you want NULLs to count as zero.</p><p>If a customer placed an order but has not paid yet, and you want to include that zero-value order in your revenue average, use COALESCE to replace the NULL before the average runs:</p><pre>SELECT AVG(COALESCE(amount, 0)) FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*YGZ_O7T2u67jRbCPQBYOrQ.png" /><figcaption>output with coalesce</figcaption></figure><p>Now all rows are included.</p><p>The NULL amounts count as zero and pull the average down accordingly.</p><blockquote><strong>Know which behavior your business logic requires before you write the query.</strong></blockquote><blockquote><strong>A wrong AVG does not throw an error.</strong></blockquote><blockquote><strong>It just silently answers a different question than the one you asked</strong></blockquote><h4>D. The column-not-in-GROUP-BY error</h4><p>Every column in your SELECT must either appear in GROUP BY or be wrapped inside an aggregate function.</p><p><strong>This will fail</strong></p><pre>-- product is in SELECT but not in GROUP BY and not aggregated<br><br>SELECT customer_id, product, SUM(amount)<br>FROM orders<br>GROUP BY customer_id;</pre><pre>ERROR: column &quot;orders.product&quot; must appear in the GROUP BY clause or be used in an aggregate function</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*hxSBRFT5RyPGSL1MdH1eDw.png" /><figcaption>output of the group by</figcaption></figure><blockquote><strong>PostgreSQL enforces this strictly</strong></blockquote><blockquote><strong>MySQL, with its default settings, does not</strong></blockquote><blockquote><em>It picks an arbitrary value for </em><em>product from within the group and returns it silently.</em></blockquote><blockquote><em>The query runs.</em></blockquote><blockquote><em>The result looks fine.</em></blockquote><blockquote><em>The </em><em>product column contains a value that is meaningless, picked at random from the group.</em></blockquote><blockquote><em>That is worse than an error</em></blockquote><blockquote><strong><em>At least PostgreSQL tells you the query is wrong.</em></strong></blockquote><blockquote><strong><em>MySQL lets you believe it is correct.</em></strong></blockquote><p><strong>Fix it by either adding </strong><strong>product to your </strong><strong>GROUP BY, or aggregating it</strong></p><pre>-- group by both customer and product<br><br>SELECT customer_id, product, SUM(amount)<br>FROM orders<br>GROUP BY customer_id, product;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*p4YiwyorWMG98Vm1kZQSAA.png" /><figcaption>th3e correct way of group by</figcaption></figure><blockquote><strong>PostgreSQL’s error here is doing you a favor</strong></blockquote><h4>E. Query Execution Order</h4><blockquote>SQL reads top to bottom</blockquote><blockquote>SQL does not execute top to bottom</blockquote><p><strong>The actual order PostgreSQL processes a query</strong></p><pre>FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY</pre><p><strong>This explains everything that trips engineers up</strong></p><ul><li>WHERE cannot filter on SUM(amount). The SUM has not run yet when WHERE executes.</li><li>HAVING can filter on SUM(amount). GROUP BY and aggregation have already run by the time HAVING executes.</li><li>ORDER BY can reference the alias total_spent defined in SELECT. SELECT ran before ORDER BY.</li><li>WHERE cannot reference the alias total_spent. SELECT has not run yet when WHERE executes.</li></ul><blockquote><strong>That last one is the one nobody warns you about</strong></blockquote><blockquote><em>You write </em><em>SELECT SUM(amount) AS total_spent and then try </em><em>WHERE total_spent &gt; 500.</em></blockquote><blockquote><em>PostgreSQL says the column does not exist.</em></blockquote><blockquote><em>Because at the stage WHERE runs, it does not.</em></blockquote><blockquote><em>SELECT has not yet assigned that alias.</em></blockquote><p><strong>Read every query in execution order, not in the order you wrote it.</strong></p><p><strong>That single habit catches more query bugs than any other practice</strong></p><h3>7. Conclusion</h3><p>You can now answer the questions that drive every product dashboard, every finance report, and every ops review.</p><ul><li>SUM for totals</li><li>COUNT for volume</li><li>AVG for typical values</li><li>MAX and MIN for the range</li><li>GROUP BY to break any of those from a single number into a per-category breakdown</li><li>HAVING to filter which categories survive</li></ul><p>These are not complicated tools. The complexity is in understanding what business question you are actually asking before you write the query.</p><p>A lot of wrong queries are not wrong because of a syntax error.</p><p>They are wrong because the engineer was solving a slightly different problem than the one the business needed solved.</p><blockquote><strong>SQL is a tool for answering questions.</strong></blockquote><blockquote><strong>Make sure you understand the question first.</strong></blockquote><p>Part 4 moves upstream from queries into schema design.</p><p><strong>We build an e-commerce database from scratch</strong></p><ul><li>deciding which tables to create</li><li>what to normalize, and</li><li>how to model relationships that stay consistent under real load.</li></ul><p>The aggregation queries you wrote in this part will be the same ones you run against the schema you are about to design.</p><p>See you there. Well, I’ll update the link here when part four is ready!</p><h3>8. Resources</h3><ul><li><strong>PostgreSQL Aggregate Functions Documentation:</strong> Complete reference for all aggregate functions in PostgreSQL. <a href="https://www.postgresql.org/docs/current/functions-aggregate.html">postgresql.org/docs/current/functions-aggregate.html</a></li><li><strong>DataLemur SQL Aggregate Functions Guide:</strong> Practical walkthrough with exercises you can run immediately. <a href="https://datalemur.com/sql-tutorial/sql-aggregate-functions">datalemur.com/sql-tutorial/sql-aggregate-functions</a></li><li><strong>LearnSQL Aggregate Functions Guide:</strong> Real-world scenarios including GROUP BY and HAVING combinations. <a href="https://learnsql.com/blog/aggregate-functions/">learnsql.com/blog/aggregate-functions</a></li><li><strong>Part 2 of this series:</strong> SQL JOINs, 5 JOIN types, NULLs as signals, and JOIN patterns you will use daily. <a href="https://imehboob.medium.com/sql-joins-in-postgresql-query-across-multiple-tables-and-actually-understand-what-you-are-asking-6b4dec98cd5c">Part 2</a></li><li><strong>Part 1 of this series:</strong> Install, setup, authentication, constraints, and CRUD from the terminal. <a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2">Part 1</a></li></ul><h3>9. Next Part</h3><p><strong>Part 4 is about database design.</strong></p><p><strong>We leave queries for a moment and go upstream:</strong></p><ul><li>how do you design a schema that does not fight you six months later?</li></ul><p>We design and build an <strong>e-commerce database from scratch,</strong> <strong>decide what to normalize and what not to</strong>, and <strong>enforce constraints at the database level</strong> before the application ever gets involved.</p><p>The aggregation queries you wrote here will run against the schema you design in the next part. I need a nap now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd1ce9bd6a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL JOINs in PostgreSQL: Query Across Multiple Tables and Actually Understand What You Are Asking |…]]></title>
            <link>https://imehboob.medium.com/sql-joins-in-postgresql-query-across-multiple-tables-and-actually-understand-what-you-are-asking-6b4dec98cd5c?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b4dec98cd5c</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[mystery]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Tue, 12 May 2026 10:48:09 GMT</pubDate>
            <atom:updated>2026-05-12T10:48:09.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL JOINs in PostgreSQL: Query Across Multiple Tables and Actually Understand What You Are Asking | Part 2</h3><p><em>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1iUUe6bWtLP3KO7cVPz1g.png" /><figcaption>image credit: grok</figcaption></figure><h3>Table of Contents</h3><ul><li>Quick Recap of Part 1</li><li>Who This Is For</li><li>What You Will Have Built by the End of Part 2</li></ul><ol><li>Why JOINs Exist</li><li>Preparing the Schema for Part 2</li><li>The 5 JOIN Types</li></ol><ul><li>A. INNER JOIN</li><li>B. LEFT JOIN</li><li>C. RIGHT JOIN</li><li>D. FULL OUTER JOIN</li><li>E. CROSS JOIN</li></ul><p>4. Patterns Worth Knowing</p><p>5. Conclusion</p><p>6. Resources</p><p>7. Next Part</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FPOdBs%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FPOdBs%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FPOdBs%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="1905" frameborder="0" scrolling="no"><a href="https://medium.com/media/476652acaca95344a06dfcb103c29eeb/href">https://medium.com/media/476652acaca95344a06dfcb103c29eeb/href</a></iframe><h3>Quick Recap of Part 1</h3><p><strong>In Part 1, we</strong></p><ul><li>installed PostgreSQL</li><li>configured peer and password authentication</li><li>created a scoped database user, and</li><li>built three tables with typed columns and enforced constraints.</li><li>We ran full CRUD from the terminal and watched Postgres reject invalid data before the application could get a say.</li></ul><p><strong>If you have not done Part 1 yet, start there: </strong><a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2"><strong>Part 1: Install, Setup, and CRUD</strong></a><strong>.</strong></p><p>In this part, we move into intermediate SQL. Specifically, how to query data that lives across multiple related tables.</p><h3>Who This Is For</h3><p>This part is tagged <strong>[Beginner]</strong>.</p><p><strong>You need Part 1 complete.</strong> PostgreSQL should be installed, testuser and testdb should exist, and you should be able to open psql and run queries.</p><p>That is all you need.</p><h3>What You Will Have Built by the End of Part 2</h3><p><strong>By the time you close this tab, you will have</strong></p><ul><li>Dropped the Part 1 orders table and rebuilt the schema from scratch with a customers table and a fresh orders table</li><li>Run all 5 JOIN types hands-on and seen the actual output each one produces</li><li>Understood WHY each JOIN type exists, not just how to write it</li><li>Seen NULLs appear when one side of a JOIN has no match, and understood what that NULL is actually telling you</li><li>Combined JOINs with WHERE and ORDER BY for real query patterns you will write daily</li></ul><h3>1. Why JOINs Exist</h3><p>You are building an order dashboard.</p><p><strong>Your manager needs one thing</strong></p><ul><li>every customer</li><li>their orders, and</li><li>how much they spent</li></ul><p>You open psql.</p><p>You run SELECT * FROM orders.</p><p>You get amounts and customer IDs. Numbers. Not names.</p><p>You run SELECT * FROM customers.</p><p>You get names. No amounts.</p><p><strong>Two tables. One question. No way to answer it from either table alone.</strong></p><p>That is the problem JOINs solve. But before we write a single JOIN query, we need to answer the more important question: <strong>why is the data split in the first place?</strong></p><h4>A. Why Data Lives in Multiple Tables</h4><p>This is intentional. It is called <strong>normalization</strong>.</p><p>Think about an e-commerce platform. Every customer can place multiple orders.</p><p>If you stored the customer’s name, email, and phone number inside every order row, Alice with 50 orders would have her information stored 50 times.</p><p>The day she changes her email, you update 50 rows. You miss three. Now your data is inconsistent.</p><p>Instead, you store Alice once in a customers table and give her a unique ID. Every order stores only that ID.</p><p>One source of truth. No duplication. No inconsistency.</p><p><strong>Analogy:</strong> think of a hospital with two registers. One has patient names and contact details. The other has appointment records.</p><p>Each appointment does not write out the patient’s full name. It writes the patient ID. When the doctor needs tomorrow’s schedule with patient names, someone pulls both registers and matches them by ID.</p><p><strong>JOINs are that matching operation. The </strong><strong>ON clause is the ID they match on.</strong></p><h4>B. Real Situations Where JOINs Matter</h4><p><strong>These are not toy examples. These are queries you will write in production</strong></p><ul><li><strong>E-commerce dashboard:</strong> “Show all orders with the customer name and city.” Customers live in one table. Orders in another.</li><li><strong>Marketing campaign:</strong> “Give me every registered customer and their last purchase amount, even if they have never bought anything.” You need everyone, including those with no orders.</li><li><strong>Inventory audit:</strong> “Which products have never been ordered?” You need to find gaps between two tables.</li><li><strong>Reconciliation report:</strong> “Show me every customer and every order, and flag where either side has no match.” Two datasets that may not fully overlap.</li></ul><p>Each of these needs a different JOIN type.</p><p><strong>Each JOIN answers a different version of the same question</strong></p><ul><li>when a row from one table has no match in the other table, what should happen to it?</li></ul><p><strong>That question is the key. Keep it in mind as we go through each type.</strong></p><h3>2. Preparing the Schema for Part 2</h3><p>The orders table from Part 1 had a simple schema: order_id, user_id, and order_date.</p><p>It referenced the users table. Part 2 uses a different schema with a new customers table and a richer orders table that includes product and amount data.</p><p>We drop the old orders table and create fresh tables.</p><p><strong>Log in to psql as testuser:</strong></p><pre>psql -U testuser -d testdb</pre><p><strong>Drop the old orders table:</strong></p><pre>DROP TABLE orders;</pre><p><strong>Create the customers table:</strong></p><pre>CREATE TABLE customers (<br>    customer_id SERIAL PRIMARY KEY,<br>    customer_name VARCHAR(50),<br>    city VARCHAR(50)<br>);</pre><p><strong>Create the new orders table:</strong></p><pre>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    customer_id INT,<br>    product VARCHAR(50),<br>    amount DECIMAL(10,2),<br>    order_date DATE,<br>    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)<br>);</pre><p>The FOREIGN KEY constraint here ties every order to a real customer in the customers table. Same principle as Part 1. Postgres will reject any order insert that references a customer_id that does not exist in customers.</p><p><strong>Insert sample data into customers:</strong></p><pre>INSERT INTO customers (customer_name, city) VALUES <br>(&#39;Alice&#39;, &#39;New York&#39;),<br>(&#39;Bob&#39;, &#39;Los Angeles&#39;),<br>(&#39;Charlie&#39;, &#39;Chicago&#39;);</pre><p><strong>Insert sample data into orders:</strong></p><pre>INSERT INTO orders (customer_id, product, amount, order_date) VALUES <br>(1, &#39;Laptop&#39;, 1200.00, &#39;2024-07-01&#39;),<br>(1, &#39;Mouse&#39;, 25.00, &#39;2024-07-02&#39;),<br>(2, &#39;Keyboard&#39;, 75.00, &#39;2024-07-02&#39;),<br>(3, &#39;Monitor&#39;, 300.00, &#39;2024-07-03&#39;),<br>(3, &#39;Tablet&#39;, 600.00, &#39;2024-07-04&#39;);</pre><p><strong>Verify both tables:</strong></p><pre>SELECT * FROM customers;<br>SELECT * FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*jJXu-LyaTH1CZ1udD2s7sw.png" /><figcaption>the customers and orders table</figcaption></figure><p>You now have 3 customers and 5 orders. Alice has 2 orders. Bob has 1. Charlie has 2. This setup is intentional. Each JOIN we run will produce different results from this same data, and you will see exactly why.</p><h3>3. The 5 JOIN Types</h3><p>Before any queries, here is the mental model.</p><p>A JOIN connects two tables using a shared column. In our case, customers.customer_id and orders.customer_id.</p><p><strong>When a row from one table has no match in the other, you have a choice:</strong></p><blockquote><strong><em>keep it or discard it.</em></strong></blockquote><ul><li>Discard both unmatched sides: <strong>INNER JOIN</strong></li><li>Keep the left, discard the right: <strong>LEFT JOIN</strong></li><li>Keep the right, discard the left: <strong>RIGHT JOIN</strong></li><li>Keep both sides regardless: <strong>FULL OUTER JOIN</strong></li><li>Combine every row with every other row: <strong>CROSS JOIN</strong></li></ul><p>Five JOIN types. Five answers to that one question about unmatched rows.</p><h4>A. INNER JOIN</h4><p><strong>The WHY</strong></p><p><strong>INNER JOIN is the strictest JOIN.</strong> It returns only rows where a match exists in both tables. If a customer has no orders, they do not appear in the result. If an order somehow references a customer that does not exist, that order does not appear either.</p><p><strong>Use</strong> <strong>INNER JOIN</strong> when incomplete data is irrelevant to your question. You only care about rows where both sides have a story.</p><p><strong>Real use case</strong></p><p>your finance team is generating invoices. An invoice only makes sense when there is both a customer and an order.</p><p>A customer who has never ordered does not get an invoice. INNER JOIN is exactly right here.</p><p><strong>Run the query:</strong></p><pre>SELECT c.customer_id, c.customer_name, o.product, o.amount <br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*EiSiyQjwiWTP-5pUPOvD2g.png" /><figcaption>inner join</figcaption></figure><p>You get 5 rows. One per order.</p><p>Alice appears twice because she has 2 orders.</p><p><strong>No customer appears without an order.</strong></p><p>All 5 orders appear because every one of them has a matching customer.</p><p>Now watch what happens when you add a customer with no orders.</p><p><strong>Insert a 4th customer with no orders:</strong></p><pre>INSERT INTO customers (customer_name, city) VALUES (&#39;Eve&#39;, &#39;Houston&#39;);</pre><p><strong>Re-run the exact same INNER JOIN query:</strong></p><pre>SELECT c.customer_id, c.customer_name, o.product, o.amount <br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*TZQqzmb5Pu9pw4x7cJIXew.png" /><figcaption>inner join: but eve does not appear since she does not have any orders</figcaption></figure><p>Eve is nowhere. She has no orders, so INNER JOIN discarded her entirely.</p><p>That is correct for an invoice report. It would be wrong for a marketing campaign.</p><p><strong>Know your question before you choose your JOIN.</strong></p><h4>B. LEFT JOIN</h4><p><strong>The WHY</strong></p><p><strong>LEFT JOIN keeps every row from the left table, whether or not a match exists in the right table.</strong></p><p>When no match is found on the right side, those columns come back as NULL.</p><p><strong>The left table is your source of truth. The right table is supplementary data that may or may not exist.</strong></p><p><strong>Real use case</strong></p><p>your marketing team is running a re-engagement campaign.</p><p>They want every registered customer.</p><p>For customers who have ordered before, they want to personalize the email with the product they bought.</p><p>For customers who have never ordered, they still want to send the email with a generic message.</p><p><strong>A LEFT JOIN gives you every customer.</strong> <strong>The NULL tells you who has no order history.</strong></p><blockquote><strong><em>That is not a missing value. That is information.</em></strong></blockquote><p><strong>Run the query:</strong></p><pre>SELECT c.customer_id, c.customer_name, o.product, o.amount <br>FROM customers c<br>LEFT JOIN orders o ON c.customer_id = o.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*HH1MtdUBqf4FPvV6UuZX0g.png" /><figcaption>eve appeared. she does not have any orders. that is information.</figcaption></figure><p>You now get 6 rows.</p><p>Eve appears.</p><p>Her product and amount are NULL.</p><p>That NULL is not an error.</p><p><strong>It is telling you Eve is a registered customer who has never placed an order.</strong></p><blockquote>T<em>hat is exactly what the marketing team needs to know.</em></blockquote><h4>C. RIGHT JOIN</h4><p><strong>The WHY</strong></p><p><strong>RIGHT JOIN is the mirror of LEFT JOIN.</strong></p><p>It keeps every row from the right table, whether or not a match exists in the left table.</p><p>When no match is found on the left side, those columns come back as NULL.</p><p><strong>The right table is now the source of truth.</strong></p><p><strong>Real use case</strong></p><p>you are auditing a data import.</p><p>Your team imported a batch of orders from a legacy system.</p><p>Some of those orders might reference customer IDs that do not exist in your current customers table.</p><p>RIGHT JOIN surfaces those orphaned orders.</p><p>The customer columns come back NULL.</p><p><strong>That is a data integrity problem you now know about before it causes trouble downstream.</strong></p><p>To demonstrate this, we need an order that references a non-existent customer.</p><p>But our current orders table has a FOREIGN KEY constraint that prevents exactly that.</p><p>So we drop and recreate orders without the constraint for this demonstration.</p><p><strong>Drop the current orders table:</strong></p><pre>DROP TABLE orders;</pre><p><strong>Recreate orders without the foreign key constraint:</strong></p><pre>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    customer_id INT,<br>    product VARCHAR(50),<br>    amount DECIMAL(10,2),<br>    order_date DATE<br>);</pre><p><strong>Insert 5 valid orders plus one orphaned order with a non-existent customer_id:</strong></p><pre>INSERT INTO orders (customer_id, product, amount, order_date) VALUES <br>(1, &#39;Laptop&#39;, 1200.00, &#39;2024-07-01&#39;),<br>(1, &#39;Mouse&#39;, 25.00, &#39;2024-07-02&#39;),<br>(2, &#39;Keyboard&#39;, 75.00, &#39;2024-07-02&#39;),<br>(3, &#39;Monitor&#39;, 300.00, &#39;2024-07-03&#39;),<br>(3, &#39;Tablet&#39;, 600.00, &#39;2024-07-04&#39;),<br>(99, &#39;Phone&#39;, 800.00, &#39;2024-07-05&#39;);</pre><p>customer_id = 99 does not exist in customers.</p><p>With the FOREIGN KEY removed, Postgres accepted the insert.</p><p>That orphaned row is now in the system.</p><p><strong>Run the RIGHT JOIN:</strong></p><pre>SELECT c.customer_id, c.customer_name, o.product, o.amount <br>FROM customers c<br>RIGHT JOIN orders o ON c.customer_id = o.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*hCBhLoJ45P2xvNxovF9BuQ.png" /><figcaption>right join: the orphaned phone order is appeared</figcaption></figure><p>All 6 orders appear.</p><p>The Phone order shows NULL for customer_name.</p><p>It exists in the right table with no matching row in the left table. RIGHT JOIN surfaced it.</p><p><strong>Any row with NULL on the left is a problem</strong>.</p><p>In a real audit, this list of NULLs tells you exactly which orders need investigation before going further.</p><blockquote><strong><em>NOTE:</em></strong></blockquote><blockquote><em>RIGHT JOIN is relatively rare in practice.</em></blockquote><blockquote><strong><em>Most of us rewrite it as a LEFT JOIN by swapping the table order:</em></strong><em> </em><em>FROM orders o LEFT JOIN customers c ON ....</em></blockquote><blockquote><em>The result is identical. Prefer whichever reads more naturally for the query.</em></blockquote><blockquote><em>The important thing is understanding what it does.</em></blockquote><p>Before moving on, restore the orders table with the foreign key.</p><p><strong>Drop and recreate orders with the constraint:</strong></p><pre>DROP TABLE orders;</pre><pre>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    customer_id INT,<br>    product VARCHAR(50),<br>    amount DECIMAL(10,2),<br>    order_date DATE,<br>    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)<br>);</pre><pre>INSERT INTO orders (customer_id, product, amount, order_date) VALUES <br>(1, &#39;Laptop&#39;, 1200.00, &#39;2024-07-01&#39;),<br>(1, &#39;Mouse&#39;, 25.00, &#39;2024-07-02&#39;),<br>(2, &#39;Keyboard&#39;, 75.00, &#39;2024-07-02&#39;),<br>(3, &#39;Monitor&#39;, 300.00, &#39;2024-07-03&#39;),<br>(3, &#39;Tablet&#39;, 600.00, &#39;2024-07-04&#39;);</pre><p>Schema restored. Eve is still in customers with no orders. We continue.</p><h4>D. FULL OUTER JOIN</h4><p><strong>The WHY</strong></p><p><strong>FULL OUTER JOIN returns every row from both tables.</strong></p><p>When a match exists, both sides are populated.</p><p>When no match exists on either side, the missing columns come back as NULL.</p><p>This is the most complete view of your data. It gives you matched pairs, plus everything on the left with no match, plus everything on the right with no match.</p><p><strong>Real use case</strong></p><p>you are merging two systems before a data migration.</p><p>System A has a customers table.</p><p>System B has an orders table.</p><p>They were built independently and may not perfectly overlap.</p><p>Before the migration, <strong>you run a reconciliation report to understand what you are working with</strong></p><ul><li>customers who have never ordered</li><li>orders referencing unknown customers, and</li><li>the clean matched pairs</li></ul><p><strong>FULL OUTER JOIN gives you all three categories in one query.</strong></p><p><strong>Run the query:</strong></p><pre>SELECT c.customer_id, c.customer_name, o.product, o.amount <br>FROM customers c<br>FULL OUTER JOIN orders o ON c.customer_id = o.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*fG22Xk065Tzy12JDVTt4gA.png" /><figcaption>full outer join</figcaption></figure><p>Every customer appears.</p><p>Every order appears.</p><p>Eve shows NULL on the order side.</p><p>If we had an orphaned order (like in the RIGHT JOIN section), it would appear with NULL on the customer side.</p><p><strong>NULL on the right side</strong></p><ul><li>a customer with no orders. A business signal.</li></ul><p><strong>NULL on the left side</strong></p><ul><li>an order with no customer. A data problem.</li></ul><p><strong>Both are data.</strong></p><p><strong>Both are signals.</strong></p><p><strong>FULL OUTER JOIN shows you everything and lets you categorize by the pattern of NULLs.</strong></p><h4>E. CROSS JOIN</h4><p><strong>The WHY</strong></p><p><strong>CROSS JOIN does not match rows.</strong></p><p>It multiplies them.</p><p>Every row from the left table gets combined with every row from the right table.</p><p>The result is every possible combination.</p><p><strong>There is no </strong><strong>ON clause.</strong> You are not matching on a shared key. You are producing a cartesian product.</p><p><strong>Real use case</strong></p><p>you are building a pricing configuration table.</p><p><strong>You have 3 subscription plans (Basic, Pro, Enterprise) and 4 billing cycles (Monthly, Quarterly, Half-Yearly, Annual).</strong></p><p>You need all 12 combinations as rows so you can set prices for each.</p><p>CROSS JOIN generates all 12 in one query, ready to be populated.</p><p><strong>Another real use case</strong></p><p>generating seed data for testing.</p><p>You have 10 product categories and 5 sales regions.</p><p>CROSS JOIN gives you 50 rows, one for every category-region pair, without writing 50 insert statements.</p><p><strong>Run the query:</strong></p><pre>SELECT c.customer_name, o.product <br>FROM customers c<br>CROSS JOIN orders o;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*K6nVBc3D1TIhvUHN2oeO9w.png" /><figcaption>cross join output</figcaption></figure><p>We have 4 customers and 5 orders.</p><p>The result is 4 × 5 = 20 rows.</p><p>Every customer is paired with every order, regardless of any real relationship between them.</p><p>This is not a useful business query for our data. It is a demonstration of the mechanics.</p><p>But when you genuinely need all combinations, nothing generates them as cleanly.</p><p><strong>One hard rule</strong></p><p><strong>know your row counts before running CROSS JOIN on large tables</strong>.</p><p>1,000 rows × 1,000 rows = 1,000,000 rows.</p><p><strong>On a production table at peak traffic, that will not end quietly.</strong></p><h3>4. Patterns Worth Knowing</h3><p>The five JOIN types are the building blocks.</p><p>In practice, you combine them with other clauses to answer real questions.</p><p>Here are the patterns you will use daily.</p><h4>A. Table Aliases</h4><p>You may have noticed c and o in the queries above. Those are table aliases.</p><p>Instead of writing customers.customer_name everywhere, you write c.customer_name.</p><p>Cleaner, shorter, and essential when queries grow longer.</p><p>You define them right after the table name in the FROM clause.</p><pre>SELECT c.customer_name, o.product, o.amount<br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id;</pre><p>c stands for customers. o stands for orders.</p><p>Use them throughout.</p><p>Every engineer reading your query will immediately know what they reference.</p><h4>B. JOIN with WHERE</h4><p>A JOIN builds the combined table. WHERE filters it.</p><p><strong>Real use case</strong></p><p>you want all orders placed in July 2024, with customer names included.</p><p><strong>Run the filtered query:</strong></p><pre>SELECT c.customer_name, o.product, o.amount, o.order_date<br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id<br>WHERE o.order_date BETWEEN &#39;2024-07-01&#39; AND &#39;2024-07-31&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xgKfCwAVr5yGM8ddZjjHjQ.png" /><figcaption>inner join with where clause</figcaption></figure><p>The JOIN happens first.</p><p>The combined table is assembled.</p><p>Then WHERE filters it down to the rows you care about.</p><p><strong>Think of it in that sequence when writing the query</strong></p><ul><li>join first</li><li>filter second.</li></ul><h4>C. JOIN with ORDER BY</h4><p>Sort the combined result like any other query.</p><p><strong>Get all orders with customer names, sorted by amount from highest to lowest:</strong></p><pre>SELECT c.customer_name, o.product, o.amount<br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id<br>ORDER BY o.amount DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*1k5et2ct9VCVYZvSUenyFA.png" /><figcaption>inner join with ordering</figcaption></figure><p>The JOIN type determines which rows you get.</p><p>WHERE decides which of those you keep.</p><p>ORDER BY decides the sequence.</p><p>Each clause does one job.</p><h4>D. What Comes Next: Aggregation</h4><p>You can also combine JOINs with aggregation functions.</p><p><strong>For example</strong>: the total amount each customer has spent.</p><p><strong>Run this query:</strong></p><pre>SELECT c.customer_name, SUM(o.amount) AS total_spent<br>FROM customers c<br>INNER JOIN orders o ON c.customer_id = o.customer_id<br>GROUP BY c.customer_name<br>ORDER BY total_spent DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*qhnjrxFsW4t2iqz0Tv05-w.png" /><figcaption>inner join with aggregation</figcaption></figure><p>This groups the joined result by customer and sums their order amounts.</p><p>GROUP BY and SUM are aggregation tools.</p><p>They are the topic of Part 3, where we will cover COUNT, AVG, HAVING, and subqueries.</p><p>Run the query above and see the output.</p><p>We will explain every part of it properly in the next part.</p><h3>5. Conclusion</h3><p>You ran all 5 JOIN types against real data and saw exactly what each one returned.</p><p>The schema changed between Part 1 and Part 2, you handled that in the terminal, and the queries carried forward cleanly.</p><p>The most important thing to take from this part is not the syntax.</p><p>It is the question each JOIN is answering.</p><p>When a row has no match on the other side, what do you want to happen to it?</p><p>Throw it away, keep it with NULLs, or keep everything and let the NULLs tell you where the gaps are.</p><p><strong>Answer that question first. Then pick the JOIN type.</strong></p><p>The dangerous mistake is not writing the wrong JOIN and getting an error.</p><p><strong>The dangerous mistake is writing the wrong JOIN and getting results that look correct but are not</strong>.</p><p><strong>A query that silently discards rows you needed is worse than one that fails loudly.</strong></p><p><strong>Part 3 covers what happens after you join</strong></p><p>GROUP BY, COUNT, SUM, AVG, HAVING, and subqueries.</p><p>The same schema carries forward. See you there.</p><h3>6. Resources</h3><ul><li><strong>PostgreSQL JOIN Documentation:</strong> Complete reference for all JOIN types with syntax and examples. <a href="https://www.postgresql.org/docs/current/queries-table-expressions.html">postgresql.org/docs/current/queries-table-expressions.html</a></li><li><strong>DataLemur SQL JOIN Guide:</strong> Practical walkthrough with diagrams for every JOIN type. <a href="https://datalemur.com/sql-tutorial/sql-joins-inner-outer-left-right">datalemur.com/sql-tutorial/sql-joins-inner-outer-left-right</a></li><li><strong>PingCAP: Mastering SQL JOINs:</strong> Extended examples and real-world JOIN patterns. <a href="https://www.pingcap.com/article/mastering-sql-joins-guide-examples/">pingcap.com/article/mastering-sql-joins-guide-examples</a></li><li><strong>Part 1 of this series:</strong> Install, setup, authentication, constraints, and CRUD from the terminal. <a href="https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2">Part 1</a></li></ul><h3>7. Next Part</h3><p>Part 3 covers intermediate SQL aggregations: GROUP BY, HAVING, COUNT, SUM, AVG, and subqueries.</p><p>We build on the same schema and write queries that answer questions like</p><p><strong>&quot;who are my top customers by total spend&quot;</strong> and<strong> &quot;which products have more than one order.&quot;</strong></p><p>The foundation you built in Parts 1 and 2 carries forward directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b4dec98cd5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install & Setup PostgreSQL, Creating Tables, and CRUD Operations | Part 1]]></title>
            <link>https://imehboob.medium.com/install-setup-postgresql-creating-tables-and-crud-operations-part-1-5fe1bed693d2?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe1bed693d2</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Tue, 12 May 2026 04:04:41 GMT</pubDate>
            <atom:updated>2026-05-13T01:01:19.209Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>PostgreSQL Mastery Series. A Practical, Follow-Along Course from Basics to Replication</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSL5qAO_9hTlBlG-yYgelg.jpeg" /><figcaption>image credit: grok</figcaption></figure><h3>Table of Contents</h3><ul><li>Why This Series Exists</li><li>Who This Is For</li><li>The Full Series at a Glance</li><li>What You Will Have Built by the End of Part 1</li><li>Install PostgreSQL</li><li>Understanding PostgreSQL Authentication (Read Before You Touch pg_hba.conf)</li><li>Log In with psql</li><li>Create a Database and User</li><li>Create Your First Table</li><li>CRUD Operations</li><li>Working with More Data Types</li><li>Constraints</li><li>Validate Constraints</li><li>Conclusion</li><li>Resources</li><li>Next Part</li></ul><h3>Why This Series Exists</h3><p>Most engineers use PostgreSQL. Fewer actually understand it.</p><p>That is not a criticism. It is just how most of us learn. You connect an ORM, write some queries, ship the feature. The app works. Nobody asks questions. Until production does.</p><p>The moment a query starts taking four seconds on a table you thought was fast, the moment you realize you never set up an index. The moment you need to debug a deadlock at 2am, you realize you never properly understood locking. The moment someone asks you to set up replication before the next sprint ends, the gap between “I use PostgreSQL” and “I understand PostgreSQL” becomes very expensive very fast.</p><p>I built this series to close that gap. Not with theory. With a terminal open and commands you run yourself.</p><p>Every part in this series is practical. You follow along. You run the commands. You see the output. By the time you finish Part 17, you will have touched every layer of PostgreSQL that matters in production, from install to master-slave replication with automated health checks.</p><p>There are plenty of PostgreSQL resources out there. The official docs are excellent. But docs assume you already know what you are looking for. This series assumes you are starting from scratch and want to come out the other side production-ready.</p><p>So? Let’s start.</p><h3>Who This Is For</h3><p>You need a Linux machine, Ubuntu or Debian preferred. You need a terminal and basic command-line comfort. That is it.</p><p>No prior PostgreSQL knowledge needed. If you have used any database before (even through an ORM), you will follow this without any friction. If this is your first database, you are in the right place.</p><h3>About This Series</h3><p><strong>This is a 17-part series on PostgreSQL</strong>.</p><p>Every part is practical.</p><p>Every command in this series is one you run yourself.</p><p>No theory dumps.</p><p>No slides.</p><p><strong>By the end of Part 17</strong>, <strong>you will have</strong></p><ul><li>installed PostgreSQL</li><li>run it on AWS</li><li>backed it up</li><li>indexed it</li><li>locked rows</li><li>pooled connections</li><li>partitioned tables, and</li><li>set up replication with a health check.</li></ul><p>From install to production-grade.</p><p><strong>17 parts. Four levels. One complete package from zero to production.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFr3Ui%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFr3Ui%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFr3Ui%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="2056" frameborder="0" scrolling="no"><a href="https://medium.com/media/2baf66a8ca1d5658cf6c94166666a529/href">https://medium.com/media/2baf66a8ca1d5658cf6c94166666a529/href</a></iframe><blockquote>Start from Part 1. Follow in order. Each part builds on what came before.</blockquote><h3>What You Will Have Built by the End of Part 1</h3><p>This part is tagged <strong>[Beginner]</strong>.</p><p><strong>By the time you close this tab, you will have</strong></p><ul><li>PostgreSQL installed and running on Linux</li><li>A custom database and a user with scoped privileges</li><li>Three tables: users, products, and orders with typed columns and enforced constraints</li><li>Full CRUD tested in the terminal: insert, read, update, delete</li><li>Watched Postgres reject invalid data before it ever reached your application</li></ul><p>That last one matters.</p><p>A lot of engineers validate data only in the application layer and trust the database to just store whatever arrives.</p><p>By the end of Part 1, you will understand why that is a bad idea and you will have seen Postgres prove it.</p><p>So? Let’s go.</p><h3>1. PostgreSQL Setup</h3><h4>A. PostgreSQL Install</h4><p><strong>Update the package list first:</strong></p><pre>sudo apt update</pre><p><strong>Install PostgreSQL along with the contrib package</strong></p><pre>sudo apt install postgresql postgresql-contrib -y</pre><p>postgresql-contrib includes extra tools and extensions that come in useful as you go deeper into the series. Worth installing from the start.</p><p><strong>Start the PostgreSQL service</strong></p><pre>sudo systemctl start postgresql</pre><p><strong>Enable it to start automatically on system boot</strong></p><pre>sudo systemctl enable postgresql</pre><p><strong>Check that the service is running</strong></p><pre>sudo systemctl status postgresql</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*VNf5hytiPN9EMRUrkcJikQ.png" /><figcaption>postgresql installed and running</figcaption></figure><p><strong>You will likely see this, that catches people off guard</strong></p><pre>Active: active (exited)</pre><p>Not active (running). That looks wrong. Well it is not.</p><p>It is an example of systemd instance templates. The postgresql.service is not the actual database process. It is a trigger.</p><p><strong>It starts the real versioned service:</strong> something like postgresql@16-main.service and then immediately exits because its job is done.</p><p>“Active (exited)” means it fired successfully and handed off.</p><p>That is expected behavior.</p><p><strong>To confirm the actual Postgres cluster is running, first list all postgreSQL-realated units</strong></p><pre>systemctl list-units &quot;postgresql*&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*1xFzvhtPyJsGBjdCeM-AQw.png" /><figcaption>list all postgresql service</figcaption></figure><p>You will see two entries. The postgresql@16-main.service is the one that matters.</p><p><strong>Check it directly</strong></p><pre>sudo systemctl status postgresql@16-main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzUGfxPSOnIxgZ_Si6wkBA.png" /><figcaption>postgresql@16-main running</figcaption></figure><p>The 16 in postgresql@16-main is your PostgreSQL version. If you installed a different version, the number changes. The rest stays the same.</p><p>If the versioned service shows active (running), you are good. Move to the next section.</p><h4>B. Understanding PostgreSQL Authentication (Read Before You Touch pg_hba.conf)</h4><p>Before you log in, there is one file worth knowing about. It will not bite you right now, but it has bitten a lot of engineers who skipped this section. So read it.</p><p>PostgreSQL controls how clients authenticate using a configuration file called pg_hba.conf. The letters stand for Host-Based Authentication.</p><p><strong>Every connection attempt:</strong> local, remote, or through a socket goes through this file first.</p><p><strong>Here is where it lives</strong></p><pre>sudo vim /etc/postgresql/16/main/pg_hba.conf</pre><p><strong>Replace </strong><strong>16 with your installed PostgreSQL version. Run below to find your postgresql version</strong></p><pre>psql --version</pre><p><strong>Inside </strong><strong>pg_hba.conf, you will find a line that looks like this</strong></p><pre>local   all             postgres                                     peer</pre><p><strong>The last column is the authentication method. Here is what each one means</strong></p><ul><li><strong>postgres</strong>: the allowed user</li><li><strong>peer: </strong>postgreSQL checks the OS username of whoever is connecting. If the OS user is postgres, it expects a PostgreSQL role also named postgres. No password needed. This is the default for local connections on Linux.</li><li><strong>md5: </strong>Password-based authentication. PostgreSQL verifies the supplied password against an MD5-hashed version stored in the database.</li><li><strong>scram-sha-256: </strong>also password-based, but uses a stronger hashing algorithm. This is the recommended choice when you want password authentication.</li></ul><p><strong>Do not change this line right now.</strong></p><p>The next section uses sudo -u postgres psql to log in. That command relies on peer authentication. it works because you are switching to the postgres OS user before connecting. If you change peer to md5 or scram-sha-256 before the postgres database role has a password set, that login command will fail and you will be locked out of your own install.</p><h4>C. Log In with psql</h4><p>Switch to the postgres OS user and <strong>open the psql interactive shell:</strong></p><pre>sudo -u postgres psql</pre><p>You are now inside psql. This is the PostgreSQL interactive shell. Every SQL command in this series gets run here.</p><p><strong>Check your connection details:</strong></p><pre>\conninfo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*6LJ-RVyq_lGCpln3AJXQxQ.png" /><figcaption>\conninfo output</figcaption></figure><p><strong>Verify the PostgreSQL version:</strong></p><pre>SELECT version();</pre><blockquote>If you are wondering what \conninfo is that psql has a set of backslash meta-commands for navigating the database.</blockquote><blockquote>They are not SQL. They are psql-specific shortcuts. You will use a few of them throughout this series.</blockquote><blockquote>\dt lists tables. \c dbname switches databases. \conninfo shows connection info.</blockquote><blockquote>That is enough for now.</blockquote><h4>D. Create a Database and User</h4><p><strong>Create a new database:</strong></p><pre>CREATE DATABASE testdb;</pre><p><strong>Create a new user with a password</strong></p><pre>CREATE USER testuser WITH PASSWORD &#39;testpassword&#39;;</pre><p><strong>Grant full privileges on </strong><strong>testdb to </strong><strong>testuser</strong></p><pre>ALTER DATABASE testdb OWNER TO testuser;</pre><p>Before logging in as testuser, you need to update the authentication method.</p><p><strong>Set password for default </strong><strong>postgres user so that we can authenticate for any administrative purpose later</strong></p><pre>ALTER USER postgres WITH PASSWORD &#39;defaultpassword&#39;;</pre><p><strong>Inside </strong><strong>pg_hba.conf, chnnge the below for secure password authentication for all user types</strong></p><pre>local   all             all                                     scram-sha-256</pre><p><strong>Restart the postgresql service</strong></p><pre>sudo systemctl restart postgresql</pre><p><strong>Exit the current shell and log back in as </strong><strong>testuser</strong></p><pre>\q<br><br>psql -U testuser -d testdb<br><br># provide the password set while creating the user </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*bNIVUWuqeT1dRt2XlJh8xg.png" /><figcaption>logged in as testuser with passoword in testdb</figcaption></figure><blockquote><strong>NOTE:</strong></blockquote><blockquote>The # prompt means superuser.</blockquote><blockquote>The &gt; prompt means regular user.</blockquote><blockquote>testuser is intentionally not a superuser.</blockquote><blockquote>That is the point.</blockquote><blockquote>In production, you never connect your application with a superuser.</blockquote><blockquote>You create a user with exactly the privileges it needs. no more.</blockquote><h4>E. Create Your First Table</h4><p><strong>Create the </strong><strong>users table</strong></p><pre>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    name TEXT NOT NULL,<br>    email TEXT UNIQUE NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p><strong>Here is what each definition does</strong></p><ul><li>SERIAL PRIMARY KEY: auto-incrementing integer. Postgres manages it. You never insert it manually.</li><li>TEXT NOT NULL : a text column that cannot be empty. An insert without a name fails.</li><li>TEXT UNIQUE NOT NULL: required, and must be unique across every row. No two users can share an email.</li><li>TIMESTAMP DEFAULT CURRENT_TIMESTAMP: automatically set to the exact time of the insert. You do not need to supply it.</li></ul><p><strong>List all tables in the current database:</strong></p><pre>\dt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*9HbZNRJ6Cisfw8speet58A.png" /><figcaption>users table</figcaption></figure><h3>2. CRUD Operations</h3><h4>A. Insert Data</h4><p><strong>Insert two records into </strong><strong>users:</strong></p><pre>INSERT INTO users (name, email) VALUES <br>(&#39;Alice&#39;, &#39;alice@example.com&#39;),<br>(&#39;Bob&#39;, &#39;bob@example.com&#39;);</pre><p>id and created_at are not in the insert. SERIAL and DEFAULT handle those automatically. You just provide what you know.</p><h4>B. Read Data</h4><p><strong>Fetch all users:</strong></p><pre>SELECT * FROM users;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*YHZdnDe94rbmlIaQZ_I3kQ.png" /><figcaption>current users in user table</figcaption></figure><p><strong>Fetch a specific user:</strong></p><pre>SELECT * FROM users WHERE name = &#39;Alice&#39;;</pre><h4>C. Update Data</h4><p><strong>Update Alice’s email:</strong></p><pre>UPDATE users SET email = &#39;alice_new@example.com&#39; WHERE name = &#39;Alice&#39;;</pre><p><strong>Verify:</strong></p><pre>SELECT * FROM users WHERE name = &#39;Alice&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*95o9IYocWMj9ZmqQvuWU1g.png" /><figcaption>updated Alice’s email</figcaption></figure><h4>D. Delete Data</h4><p><strong>Delete Bob:</strong></p><pre>DELETE FROM users WHERE name = &#39;Bob&#39;;</pre><p><strong>Verify:</strong></p><pre>SELECT * FROM users;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*H_h3FnremtZttTAL93e49Q.png" /><figcaption>Bob user deleted</figcaption></figure><p>That is full CRUD.</p><p>Four operations.</p><p>That is everything your application does to a table, every single day.</p><p>Now let’s add some depth.</p><h3>2. Working with More Data Types</h3><p>The users table used TEXT, SERIAL, and TIMESTAMP.</p><p><strong>Let&#39;s build a </strong><strong>products table that introduces a wider range of types</strong></p><pre>CREATE TABLE products (<br>    id SERIAL PRIMARY KEY,<br>    name TEXT NOT NULL,<br>    price DECIMAL(10,2) CHECK (price &gt; 0),<br>    in_stock BOOLEAN DEFAULT TRUE,<br>    created_at DATE DEFAULT CURRENT_DATE,<br>    metadata JSONB<br>);</pre><p><strong>Here is what is new:</strong></p><ul><li>DECIMAL(10,2): precise decimal storage. Up to 10 digits total, 2 after the decimal point. Use this for monetary values. Never use FLOAT for money.</li><li>BOOLEAN DEFAULT TRUE: true or false. Defaults to TRUE here, meaning every new product is assumed in stock until told otherwise.</li><li>DATE: stores only the date, no time component. Different from TIMESTAMP.</li><li>JSONB: binary-encoded JSON. Use it when the shape of your data is genuinely unknown at design time, or when you need to query inside the JSON using Postgres operators. If the structure is known, a proper typed column is cleaner and significantly faster. JSONB is a tool, not a habit.</li></ul><p><strong>Run </strong><strong>\dt again:</strong></p><pre>\dt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*jTQ8iYOHjGqcxcWFEolzdg.png" /><figcaption>products table</figcaption></figure><h3>4. Constraints</h3><p>Constraints are rules enforced at the database level. Not in your Django model. Not in your Express middleware. In the database itself — before any row is ever written.</p><p>This matters because application-layer validation can be skipped, misconfigured, or bypassed. Database constraints cannot. If a row violates a constraint, Postgres rejects the insert. Full stop.</p><h4>A. CHECK Constraint</h4><p><strong>Add an </strong><strong>age column to </strong><strong>users with a CHECK</strong></p><pre>ALTER TABLE users ADD COLUMN age INTEGER CHECK (age &gt;= 18);</pre><p>Any insert with age &lt; 18 will be rejected by Postgres directly. Your application never sees the bad data go in. It just gets an error back.</p><p><strong>Verify the updated schema</strong></p><pre>SELECT * FROM users;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*89ejcCUuCOW8g0PKXuNDTQ.png" /><figcaption>users model with new age column</figcaption></figure><h4><strong>B. FOREIGN KEY Constraint</strong></h4><p><strong>Create an </strong><strong>orders table that references </strong><strong>users</strong></p><pre>CREATE TABLE orders (<br>    order_id SERIAL PRIMARY KEY,<br>    user_id INTEGER REFERENCES users(id),<br>    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>The REFERENCES users(id) part is the foreign key. Postgres will reject any insert into orders where the user_id does not match an existing id in users. You cannot create an order for a user who does not exist. Postgres will not silently accept orphaned data.</p><p>This is the kind of integrity that ORMs say they give you. The database actually gives it to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*fJz8OvTyfbNcoh4yxGvgrw.png" /><figcaption>all created tables</figcaption></figure><h4>C. Validate Constraints</h4><p><strong>Insert a valid user</strong></p><pre>INSERT INTO users (name, email, age) VALUES (&#39;Charlie&#39;, &#39;charlie@example.com&#39;, 25);</pre><p><strong>Now try inserting a user who is 15</strong></p><pre>INSERT INTO users (name, email, age) VALUES (&#39;David&#39;, &#39;david@example.com&#39;, 15);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*p5TbWpay6vCnrJsyVNHJ0w.png" /><figcaption>constraint failed for age</figcaption></figure><p>Postgres rejected David.</p><p>Not your application.</p><p>Not your serializer.</p><p>Postgres.</p><p>Before the row was written.</p><p>Before any downstream code ran.</p><p><strong>Now check the final state of the table</strong></p><pre>SELECT * FROM users;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*BfUZd5JZig-d0n3AE947ig.png" /><figcaption>updated user model wiyth age constraint</figcaption></figure><p>That is constraints working exactly as intended. And you did not write a single line of application code to make that happen.</p><h3>5. Conclusion</h3><p>You just went from from zero to</p><ul><li>a running PostgreSQL instance with a custom database</li><li>a scoped user</li><li>multiple tables with typed columns and enforced constraints</li><li>and full CRUD tested from the terminal.</li></ul><p>The constraint validation at the end is the part worth sitting with. The age &gt;= 18 check stopped David from being inserted before the application ever got a say.</p><p>That is the database doing its job. Most engineers give that job to the application layer and then wonder how dirty data ends up in production.</p><p>Now that the foundation is in place, Part 2 moves into intermediate SQL JOINs, subqueries, and multi-table queries. The database you just built carries forward. No fresh setup needed.</p><h3>6. Resources</h3><ul><li><strong>PostgreSQL Official Documentation:</strong> The complete reference. Start here when something is unclear. <a href="https://www.postgresql.org/docs/">postgresql.org/docs</a></li><li><strong>psql Meta-Commands Reference:</strong> Full list of backslash commands — \dt, \c, \conninfo, and more. <a href="https://www.postgresql.org/docs/current/app-psql.html">postgresql.org/docs/current/app-psql.html</a></li><li><strong>PostgreSQL Data Types:</strong> Full reference for all supported types with exact behavior. <a href="https://www.postgresql.org/docs/current/datatype.html">postgresql.org/docs/current/datatype.html</a></li><li><strong>pg_hba.conf Authentication Methods:</strong> Every authentication option explained in detail. <a href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">postgresql.org/docs/current/auth-pg-hba-conf.html</a></li></ul><h3>7. Next Part</h3><p>Part 2 covers intermediate SQL in PostgreSQL such as JOINs, subqueries, HAVING, and writing queries that span multiple related tables.</p><p>Your next step should be tinkering more with teh commands we have discussed here. Read more blogs, ask AI for any specific question may arise.</p><p><strong>Read the part two here: </strong><a href="https://imehboob.medium.com/sql-joins-in-postgresql-query-across-multiple-tables-and-actually-understand-what-you-are-asking-6b4dec98cd5c"><strong>SQL JOINs in PostgreSQL: Query Across Multiple Tables and Actually Understand What You Are Asking | Part 2</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe1bed693d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drishti AI: Building an AI Eye Screening Agent for Rural India in 7 Days]]></title>
            <link>https://imehboob.medium.com/drishti-ai-building-an-ai-eye-screening-agent-for-rural-india-in-7-days-2fc3d4ccc1fe?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc3d4ccc1fe</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[roboflow]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 15:43:22 GMT</pubDate>
            <atom:updated>2026-03-05T03:06:40.300Z</atom:updated>
            <content:encoded><![CDATA[<p>WeMakeDevs and Vistion Agents Hackathon in Action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1KGRTwwXBof6OyxA4JSpg.png" /><figcaption><a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHA</a> worker screening eye of rural woman with Drishti AI</figcaption></figure><h3>TL;DR; What is Drishti AI</h3><p>I signed up for the <a href="https://www.wemakedevs.org/hackathons/vision">WeMakeDevs Vision Agents</a> Hackathon at the end of February without a clear idea of what I was going to build. You know how it is, you see a hackathon, the tech looks interesting, you register, and then you figure out the idea later.</p><p><a href="https://visionagents.ai/">Vision Agents</a> is an <a href="https://github.com/GetStream/vision-agents">Open Source SDK</a> from <a href="https://getstream.io/">GetStream</a> that lets you build AI agents that can see and hear in real time through WebRTC. It lets an AI model see and hear on a live video call, not just process uploaded images. I had a week to build something with it.</p><p>What I ended up building was <a href="https://github.com/Mahboob-A/drishti-ai">Drishti AI</a>, a real-time AI eye screening system for rural India that puts an AI agent in an <a href="https://en.wikipedia.org/wiki/Accredited_Social_Health_Activist">ASHA</a> worker’s phone to screen eyes, speak Hindi, and refer patients to their nearest health centre. Most of the week was planning, building, and fixing bugs. Let me walk you through how it went.</p><h3><strong>What’s in this post</strong></h3><h4><strong>My Hackathon Week</strong></h4><p>Feb 23 — Getting Started</p><p>Feb 24 — Finding the Problem</p><p>Feb 25 — Planning Day</p><p>Feb 26–27 — Building with AI Assisted Development</p><p>Feb 28 — The Hardest Day</p><p>March 1 — First Eye Screening</p><h4><strong>How Drishti AI Works</strong></h4><p>Architecture Overview</p><p>The Android App</p><p>The Vision Agent Session</p><p>Post-Screening Data Flow</p><p>Monitoring Stack</p><p>The Full Data Flow</p><p>The Deployment Situation</p><p>Closing Thoughts</p><h4>Github</h4><p><strong>Github Repo Link:</strong> <a href="https://github.com/Mahboob-A/drishti-ai">https://github.com/Mahboob-A/drishti-ai</a></p><h4>YouTube</h4><p><strong>YouTube Video:</strong> <a href="https://youtu.be/8LUT89UYnSc">https://youtu.be/8LUT89UYnSc</a></p><h3>My Hackathon Week</h3><h4>Feb 23 — Getting Started</h4><p>On Feb 23 I started by reading the Vision Agents SDK docs and running a few sample projects. I wanted to understand the basic call flow and what events I would get when media tracks show up. I also checked what was needed for TURN, since I knew NAT issues could come up later. After that, I set up a small repo and ran the sample agent locally. The goal for the day was simple, get one call to connect from my laptop and see logs from the agent.</p><h4>Feb 24 — Finding the Problem</h4><p>On Feb 24 I still did not have an idea. I listed a few areas I could build in a week, like education, clinic intake, and simple triage. I talked to my mom about common health issues she sees around her. She mentioned her own eye checkups and how many people delay them until they cannot see well. That stuck with me because it is easy to ignore vision problems until they get worse.</p><p>I spent the afternoon reading about rural health workflows in India. India has around 12 million blind people, and a large part of that is preventable or treatable. The gap is mostly about timing and access. <a href="https://en.wikipedia.org/wiki/Accredited_Social_Health_Activist">ASHA</a> workers are community health workers who connect villages to the public health system. There are roughly a million of them across India, they already do household visits, and they already carry smartphones. I started thinking about an app that could guide an <a href="https://en.wikipedia.org/wiki/Accredited_Social_Health_Activist">ASHA</a> worker through a short eye screening, collect symptoms, and store results for a doctor to review later. I did not want to pretend it could diagnose anything. I wanted it to be a structured intake that is easier to run and easier to record.</p><p>I also wrote down what the agent should say and what the worker should see on the phone screen. The first version was just a question flow, in Hindi, wiht short prompts and clear confirmations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*l_byUyuJniLXEKt5Q6Vgug.jpeg" /><figcaption>The project setup I settled with after a lot of trial and errors</figcaption></figure><h4>Feb 25 — Planning Day</h4><p>I did not have much time, so I planned all the docs first and made a few revisions. SRS, BRD, system design, API contracts, data models. They were not perfect, but I wanted to start building since I believe getting something running is half the success, and the rest you figure out during the actual work. I know, I know, docs feel slow in a hackathon, but it saved me time later.</p><p>I decided on four services: Django for the backend, FastAPI for the AI agent, React Native for the Android app, and React web for the admin dashboard. I sketched the request flow, what happens when a screening session starts, and what gets stored. I kept auth basic and focused on getting a full run working end to end. I also planned to use AI coding agents to help with scaffolding and tests, but I would steer every step myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MxmIBB6AIHJmTx4nq134A.png" /><figcaption>The inter-service communication of Drishti AI</figcaption></figure><h4>Feb 26–27 — Building with AI Assisted Development Flow</h4><p>Feb 26 and 27 were mostly implementation. I set up a <strong>monorepo</strong> so I could move faster between services. I added shared env templates and a single command to bring most things up locally. The repo structure was straightforward, <strong>backend, agent, mobile, and admin</strong> in separate folders.</p><p><strong>On the Django side, I built patient, session, and screening models</strong>. I then setup CRUD endpoints and added test coverage as I went. By the end, the <strong>backend test suite was at 234 tests</strong> covering auth, family management, screening sessions, the internal API, and the admin dashboard. I also ended up doing more migrations than I expected because I kept adjusting fields as the flow became clearer. That was probabaly avoidable, but it helped me keep the data model aligned with the screens.</p><p><strong>On the FastAPI side, I built the agent service with the 5-layer pipeline, session endpoints, and the core orchestration</strong>. That suite reached 275 tests. <strong>On Android, I built the login, patient selection, pre-session checks, live session screen, and results view</strong>. I focused on simple UI, big buttons, and clear text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8IA5f74u5HrBG__fhKdOg.png" /><figcaption>The monorepo structure of Drishti AI</figcaption></figure><h4>Feb 28 — The Hardest Day</h4><p>Feb 28 is when things started breaking. The call was connecting fine. The ICE connection showed completed, the logs looked healthy, and the agent joined the session. But sadly, there was no audio. I could see the session events and the track callbacks, but I could not hear the agent speak, and the agent could not hear me.</p><p>I spent the first couple hours checking the Android side. Metro was building fine and the app was loading without issues. The bundler output was clean, so it did not look like a packaging problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*036jTaaN01KexzoNwsb5jQ.png" /><figcaption>Metro bundler successful</figcaption></figure><p>I also double checked the login and basic navigation, because I had changed some auth wiring the night before. The app screens were fine, it was just the media.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vVDxCTD_3RJu3jWz0tL5XA.jpeg" /><figcaption>Android app successfully connected</figcaption></figure><p>Then I went back to the agent and infra. I found several issues one after another. The first was the <em>platforms</em> key in docker-compose.dev.yml being invalid for my setup. Then the inference package was missing dependencies because I had installed it with <em>— no-deps</em>. Then Roboflow returned <em>403s </em>because the model ID format was wrong. And the <em>metro.config.js</em> refused to import shared constants across project boundaries. Each fix uncovered the net problem.</p><p>The biggest problem turned out to be Docker networking on macOS. WebRTC inside Docker was doing a <strong><em>double-NAT </em></strong>thing where signaling worked and ICE completed, but media bytes never actually arrived inside the container. So the agent “<strong>joined</strong>” but could not hear anything. On top of that, TURN credentials were getting deserialized as <strong>None</strong> from the <strong><em>JoinCallResponse</em></strong>, so even when I thought I had relay options, I did not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jani00EcJfEovGV0dNMgfQ.png" /><figcaption>I had to run Fastapi on native machine to fix the double nat issue in macos</figcaption></figure><p>Around midnight I was thinking about whether to just submit without the live agent. I could record a video, I could fake the audio. But that felt wrong because if I am building an agent that screens eyes, it has to at least talk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl4mlC0wDxwC9OB2v-msUg.jpeg" /><figcaption>Finally ICE state connecting to connected!</figcaption></figure><p>The fix was to move FastAPI out of Docker so WebRTC would stop getting blocked by network layers, fix the TURN credentials parsing so the client could actually recieve relay config, and correct the Gemini model ID. After that, I restarted the session. This time the agent spoke. Hindi, clear. It greeted the user and started the screening protocol. I sat there for a minute just listening to it work, because after two days of teh audio not working, it was good to finally hear it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmfKzz_iAwnPza6LEWBg7A.jpeg" /><figcaption>FINALLLY the audio track established!! I really thought to give up until I saw this!</figcaption></figure><h4>March 1 — First Eye Screening</h4><p>On March 1 I ran the first full flow without changing code between steps.</p><p><strong>I</strong> <strong>opened the Android app, logged in, selected a patient, and started a screening session</strong>.</p><p><strong>The agent joined, introduced itself, and asked the scripted questions in Hindi</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHFdpLFwQNMeB3Tq7gbmbQ.png" /><figcaption>Finalllyy the agent talked!!!</figcaption></figure><p>I answered from the device mic (mimicing an ASHA worker) and watched the backend store the responses. Then I opened the admin dashboard and confirmed the session data was saved with timestamps and links back to the patient. It was still a demo, but the flow was complete, and the pieces were connected the way I planned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h6uEcc2wmap8b98UKU34g.png" /><figcaption>The conversation with agent and prometheus metric log collection of Agent session</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*IaS--YL4ObnRziSg_U7UaA.jpeg" /><figcaption>I checkedup my eye with Drishti AI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*yPsTPgaglftNCAUkx-JFiQ.jpeg" /><figcaption>And the result: my eyes seems to be good as per Drishti AI!</figcaption></figure><p>Now let me walk you through how the system actually works.</p><h3>How Drishti AI Works</h3><h4>Architecture Overview</h4><p>Drishti AI runs as 4 services plus supporting infra. In my local setup that becomes 9 Docker containers. I split it into four services so if one part breaks, it does not take down the other three. In practice this means Django can keep handling logins and data even if the Vision Agent is crashing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIVHZDrZMqu8enIDf8i0Vw.png" /><figcaption>The system architecture of Drishti AI</figcaption></figure><p><strong>A. Django Service</strong></p><p>Django on port 8000 is the main backend. Auth, family and patient CRUD, screening sessions, the internal API, and the admin dashboard all go through Django. Django owns the database schema and is the only service that writes to PostgreSQL directly. It has 234 tests.</p><p><strong>B. FastAPI Agent Service</strong></p><p>FastAPI on port 8001 runs the Vision Agent. It manages WebRTC sessions, the 5-layer ML pipeline, tool calls, and metrics. FastAPI does not write to the database directly. It sends results to Django through an internal API. It has 275 tests.</p><p><strong>C. Android App</strong></p><p>React Native (Expo SDK 55) is the <a href="https://en.wikipedia.org/wiki/Accredited_Social_Health_Activist">ASHA</a> Android app. It handles registration, patient selection, and the guided screening flow. React Web (Vite) is the PHC admin dashboard for approvals and basic reporting.</p><p><strong>D. Other Services</strong></p><p>Supporting services are PostgreSQL, Redis, Celery, Prometheus, Grafana, and Nginx. Redis is used for queues and short-lived state. Celery runs background jobs like stale session cleanup and PIN lockout. Prometheus scrapes metrics and Grafana shows dashboards.</p><p><strong>E. Nginx Route Handling</strong></p><p>Nginx handles routing: `/api/*` goes to Django, `/agent/*` goes to FastAPI, `/grafana/*` goes to Grafana, and `/*` goes to React web static files. When a session ends, FastAPI POSTs results to Django at `/api/internal/save-session-results/` with an `X-Internal-Key` header so Django can reject random traffic.</p><h4>The Android App</h4><p>The Android app is made for <a href="https://en.wikipedia.org/wiki/Accredited_Social_Health_Activist">ASHA</a> workers in rural India, so the UI is plain on purpose. It keeps the number of taps low and the text large.</p><p>Registration collects name, village, district, block, affiliated PHC, phone number, and a 4-digit PIN. There is no OTP. This was a time choice and a field reality choice, because phones may not have stable SMS access during outreach. After registration, a PHC admin approves the account. Only then the <a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHA</a> can log in. Well! The account data is saved and can be approved later.</p><p>The app uses a Family model. The family mobile number is the key. Family members falls under it. Each member gets a `FAM-XXXXXX` ID. This makes it easier to add siblings or elders without re-entering address info every time.</p><blockquote>Patients are grouped by age so the screening questions can stay relevant: <strong>NEONATE, INFANT, CHILD, ADOLESCENT, ADULT, ADULT_PREGNANT, ADULT_LACTATING, ELDERLY</strong>.</blockquote><blockquote><strong>The screening flow is</strong>:</blockquote><blockquote>select patient, start session, confirm known conditions (if any), and begin. After the AI results come back, the <a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHA</a> can add her own assessment. She can override severity, add referral advice, and write notes.</blockquote><blockquote>This is important because the phone camera and the real situation do not always match the model’s assumptions.</blockquote><h4>Android App Tour</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*i0DEVCdBb1Te7eiW94uvfg.jpeg" /><figcaption>The Asha worker’s home page. Shows “today’s” total eye screening and recent eye screening details</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PS5TmmzORhnz37PNfVDnxg.jpeg" /><figcaption>Family are atomic core of Drishti AI — A family must be created to screen eye</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7QCQ-bBlcPud7cercNYXjw.jpeg" /><figcaption>Inside a family — A family member falls under a family for eye screening</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*TIpL3uKtpPwg2BwmmNBx-Q.jpeg" /><figcaption>Add a family member inside a family, with age based pre-set eye disease profile (see age section), with any previous pre-conditions with lactating mother and pregnant woman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8RgyYgOCwLIn-8vp1SYiBg.jpeg" /><figcaption>Inside a family member — from a family member, Asha worker can start eye screening and see previous eye screening results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*voCxsp0R-FdhKIpDCJATgA.jpeg" /><figcaption>The final page a Asha worker sees the type of eye diseases will be accessed by Drishti AI, which is categoried based on Age of a family member (See the Android App initial section to understand it better)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*F4lUxFJKaltizQaUwfrhdw.jpeg" /><figcaption>Eye screening result — by Drishti AI. Asha worker may also provide her opinion in the final restult.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*M_sQdWR0v9np-nj-TciAug.jpeg" /><figcaption>Eye screening history of all persons a Asha worker has tested with Drishti AI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*c7Zcc-L9qKJLL-7bL-JQaA.jpeg" /><figcaption>Profile page of Asha worker</figcaption></figure><h4>The Vision Agent Session</h4><p>The session works like a video call where the other person is AI. The phone streams audio and video up, and the agent streams audio back, in real time.</p><p>The Android app starts by calling FastAPI at `/agent/session/start/`. FastAPI creates a Stream Video call, then spawns a Gemini Live session using `gemini-2.0-flash-live-001`. FastAPI joins the call using the Vision Agents SDK. From there, the agent can hear the user and see frames from the camera feed. The phone publishes media to Stream’s SFU, which picks the Mumbai edge server because that is closest for most India traffic.</p><h4>Here’s the each layer of hte Vision Agent Session Runs</h4><p><strong>A. Layer 1 — The Mediapipe Face Mesh</strong></p><p>Layer 1 is MediaPipe face mesh. It finds the eyes in the frame, measures 478 face landmarks, and crops out the eye regions. It runs under 5ms. The rest of the pipeline works on these eye crops, not on the full camera frame.</p><p><strong>B. Layer 2 — The OpenCV</strong></p><p>Layer 2 is OpenCV color analysis on the crops only. It checks for redness, pallor, and jaundice-like tint. It runs under 2ms because it is only looking at the cropped regions, not the full frame. Between these layers, there is best-frame tracking. The session keeps a rolling window of recent eye crops and picks the sharpest one based on focus metrics, so we do not waste model calls on blurry frames.</p><p><strong>C. Layer 3 — The Roboflow Inrefence</strong></p><p>Layer 3 is Roboflow inference. I cap it at max 2 calls per session because it costs time and resources. I use three models: `ocular-diseases/1`, `strabismus-detector/2`, and `leukocoria-detector-rsl8x/2`. These run only on the selected best frames for right and left eye. The output is labels and confidence scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cc5Qs12vxmXdWJAgl7eFgA.png" /><figcaption><a href="https://universe.roboflow.com/projects-dmmza/ocular-diseases">Ocular diseases</a> Computer Vision Model</figcaption></figure><p><strong>D. Layer 4 — The Moondream VQA</strong></p><p>Layer 4 is Moondream VQA. It answers targeted visual questions for three conditions: conjunctivitis, corneal opacity, and xanthelasma. This layer is slower than OpenCV but works as a second opinion when Roboflow output is uncertain.</p><p><strong>E. Layer 5 — The Gemini</strong></p><p>Layer 5 is Gemini. It takes the output from all four layers plus the questionnaire answers and produces a Hindi summary wiht a severity level and recommendation. It also calls two tools during the session: `run_pathology_check` for final scoring and severity mapping, and `save_screening_result` to persist everything to Django.</p><p>The session follows a fixed sequence: greeting, questions, right eye capture, left eye capture, summary in Hindi, and save.</p><p>Each step finishes before the next one starts. Questions are age-appropriate. Neonates get observable symptoms like discharge, swelling, and light sensitivity. Elderly users get medication history and diabetes prompts because it changes how you interpret some findings.</p><h4>Post-Screening Data Flow</h4><p>When Gemini calls `save_screening_result`, FastAPI aggregates outputs from all layers into one payload. It includes per-condition signals, confidence values, and the final severity mapping. FastAPI POSTs this to Django at `/api/internal/save-session-results/` with a 3-attempt retry and 2-second backoff. If all retries fail, FastAPI marks the session as unsaved and exposes it in metrics.</p><p>Django receives the payload, validates the internal key, and saves `ScreeningResult` rows, one per condition per screening session. The Android app fetches results and shows severity badges, confidence percentages, and referral guidance. The <a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHA</a> can add her assessment too: severity override, hospital referral yes or no, and notes.</p><blockquote>The six severity levels are: <strong>NONE, MILD, MODERATE, SIGNIFICANT, SEVERE, IMMEDIATE.</strong></blockquote><h3>PHC (Primary Health Center) Local Healthcare Admin Dashboard</h3><p>The PHC admin web dashboard also shows <a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHA</a> approvals, stats, and varioud kinds of alerts. SEVERE and IMMEDIATE results get auto-flagged in the admin list. Admin are district separated. Admin must approve an Asha’s onboarding through the dashboard.</p><p>All the eye screening sessions of the jurisdictio nof a PHC can be seen by admin or doctors with all the relevant information such as family head name, mobile number, Asha’s name and mobile number.</p><p>Any severe or critical case flagged by Drishti AI or Asha can be separately monitored in the dashboard, so that doctor or admin can directly co-ordinate for speedy healthcare fascility to the patient.</p><p>See the below snaps for admin dashboard to understand more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2upRPVEP05hvFCPqBbjwQ.png" /><figcaption>The main dashboard page for PHC admin. Total number of high severity or critical cases can be seen here.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lSl2nrzawjtkMTFB9VHuQ.png" /><figcaption>New Asha registration from Drishti AI mobile app are sent in this page of the dashboard, which an admin must approve to onboard the Asha worker.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STdkNcNGZmP4zul8OnXARQ.png" /><figcaption>All the asha’s list can be seen here</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzZ0Ph6RRQUhWmP1zv9Hsw.png" /><figcaption>All the eye screening by all the Asha under the PHC can be seen here</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahTkTzuoxjpigP8GevN2lQ.png" /><figcaption>Any high severity or critical cases are flagged in this page. Doctors or admin can directly make a phone call to Asha or the family head to speedy medical fascility</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwEI6idErSWVRa1rJ6zWhQ.png" /><figcaption>The grafana dashboard is integrated inside the PHC admin. Admin can see the total session concurrently ongoing, and other Drishti AI related meta monitoring</figcaption></figure><p>Drishti AI wins at the High Severity page of the PHC dashboard. If any patient’s eye screening is marked as “high severity” or “critical” by either Drishti AI or by the Asha worker, these cases are shown here.</p><p>Then the admin may immediately contact the Asha worker or the family head to gather more informaiton about the patient. The admin may also contact the respective eye specialist doctor in the PHC for speedy medical proceedings at the earliest.</p><h3>Monitoring Stack</h3><p>Beside the grafana dashboard’s availability at the PHC admin dashboard, the grafana dashboard is also available at a dedicated endpoint.</p><p><strong>Prometheus scrapes FastAPI</strong> at `/metrics/` every 15 seconds. I have 7 collectors: `sessions_started`, `sessions_completed`, `sessions_abandoned`, `conditions_flagged`, `active_sessions`, `layer_inference_seconds`, and `gemini_response_latency`. Grafana reads Prometheus and turns these into dashboards.</p><p>The `/grafana` endpoint has to offer below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEacrA7tIfyC8bQ6m4o4SA.png" /><figcaption>The dedicated grafana dashboard at /grafana endpoint</figcaption></figure><h3>The Full Data Flow</h3><p><strong>The full path is</strong>: Android sends the request through Nginx to Django, which creates the session. <strong>FastAPI starts the agent</strong>, <strong>Stream SFU</strong> handles the WebRTC call between the <strong>phone and the AI</strong>, <strong>Gemini processes the live audio and video</strong>, <strong>FastAPI runs tool calls through Roboflow and Moondream</strong> at protocol checkpoints,<strong> and when it is done, FastAPI sends the results back to Django</strong>, <strong>which saves them to PostgreSQL</strong>. <strong>Android then fetches the results and shows them to the </strong><a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226"><strong>ASHA</strong></a><strong> worker.</strong></p><p><strong>No video frames are stored anywhere</strong>. Frames are processed in memory for the active session only. After the session ends, only the condition results and metadata are saved.</p><h3>The Deployment Situation</h3><p>My 5th AWS free tier account expired. I have run out of new debit cards and new mobile numbers to create another one. I tried GCP and they wanted Rs. 1000 to open a free tier account! Well! amm, I am trying to find another debit card and a new number to open my 6th AWS free tire till I deploy Drishti AI in it!</p><p>So the project runs on localhost for now. It runs on a Mac Mini M4, all 9 containers up, <strong>all 500+ tests passing</strong>. <strong>Django has 234 tests and FastAPI has 275 tests</strong>. <strong>This is probabaly the most stable thing in the repo right now</strong>. But the code is all there, every line of it.</p><p>Check it out: <a href="https://github.com/Mahboob-A/drishti-ai">https://github.com/Mahboob-A/drishti-ai</a></p><h3>Well, Conclusion</h3><p>This was built in 7 days. It checks 11 conditions across 8 patient groups. The agent speaks Hindi and follows a fixed session script so <a href="https://nhm.gov.in/index1.php%3Flang%3D1%26level%3D1%26sublinkid%3D150%26lid%3D226">ASHAs</a> can predict what happens next. The backend has 500+ tests, which helped catch silly regressions in teh last two days.</p><p>Next step is a small field pilot to see how camera quality, network reliability, and real patient interactions in a real deployed enviromnent compare to what I tested on localhost. Repo: <a href="https://github.com/Mahboob-A/drishti-ai">https://github.com/Mahboob-A/drishti-ai</a></p><p>Peace!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc3d4ccc1fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by Step Guide to Deploy Redis Cluster in AWS to Achieve High Availability | Part 2]]></title>
            <link>https://imehboob.medium.com/step-by-step-guide-to-deploy-redis-cluster-in-aws-to-achieve-high-availability-part-2-93d96afdb2b4?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/93d96afdb2b4</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 14:44:46 GMT</pubDate>
            <atom:updated>2025-03-26T14:44:46.411Z</atom:updated>
            <content:encoded><![CDATA[<h4>Highly Available System with Redis Cluster for Dummies | <a href="https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b">Part 2</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*zwbcLb3lpD7z2w-v6YES8Q.png" /></figure><h3>Table of Contents</h3><ul><li>Intended Audience</li><li>Learning Structure</li><li>Mode of Learning</li><li>Outcome of Learning</li><li>Recap of Part 1</li><li>Pulumi</li><li>Hands on Deployment of Cluster</li><li>Summary</li></ul><h3>Intended Audience, Learning Structure, Mode of Learning</h3><p>Please refer to the first part of the series <a href="https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b">here</a>.</p><h3>Let’s Recap Part 1</h3><p><a href="https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b">In Part 1</a>, we covered the theory behind Redis single-node and multi-node setups, their working principles, and their use cases. We also discussed High Availability (HA) and explored how to design a highly available Redis architecture.</p><p>If you’re unfamiliar with Redis single-node and multi-node setups, Replication, Sentinel, or Cluster, I’d recommend to read <a href="https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b">the Part 1</a> to understand the foundational concepts before moving on to the step-by-step Cluster deployment in AWS.</p><h3>Introduction</h3><p>In this Part 2 of the Redis Series, we will <strong>deploy a Redis Cluster in an AWS</strong> <strong>environment</strong>. We’ll design the AWS infrastructure using <a href="https://www.pulumi.com/">Pulumi</a>. <a href="https://spacelift.io/blog/what-is-pulumi">Pulumi</a> is an <strong>IaC </strong>(<em>Infrastructure as Code</em>) platform that automates cloud infrastructure management.</p><p>However, in this particular post, we will not focus on a production-level Cluster deployment. Instead, <strong>we will understand the key components involved in this process</strong> and the essential concepts required to deploy a Redis Cluster in the cloud.</p><p>In the later part of this series, we’ll extend the deployment to a more secure AWS environment, <strong>incorporating production-grade security and best practices.</strong></p><h3>Guide Overview</h3><p>In this hands-on guide, we’ll use Pulumi to provision an AWS environment. The setup includes:</p><ul><li>A VPC with three subnets.</li><li>Six EC2 instances for the Redis Cluster (Three master node, three replica node for each master node).</li><li>An additional EC2 instance for a Django application to test the Cluster.</li></ul><p>The Cluster will communicate internally using AWS private IPs.</p><p>Once everything is set up, we’ll test the Cluster by adding a key-value to the system and retrieving it. As a final touch, we’ll also set and get keys directly from the Cluster.</p><p>Let’s begin!</p><h3>Prerequisites</h3><p>To follow along the tutorial, you’ll need —</p><p>A. You need to create an account in <a href="https://www.pulumi.com/">Pulumi</a> for this tutorial to obtain an access token to provision our infrastructure in AWS. You also need to install Pulumi on your system. I assume you have a basic understanding of Pulumi. Don’t worry — you only need to know the basics. You can read this <strong>introductory lesson on Pulumi</strong> <a href="https://www.pulumi.com/docs/iac/get-started/aws/">here</a>.</p><p>B. You also need to create an<a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html"> IAM user</a> with full EC2 access. Learn more about <strong>creating an IAM role with EC2 access</strong> <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html">here</a>.</p><p>C. Additionally, you need to install the AWS CLI on your system. Please refer to this <strong>guide to install the AWS CLI</strong> <a href="https://aws.amazon.com/cli/">here</a>.</p><p>Once everything is ready, let’s begin designing the infrastructure with Pulumi.</p><h3>Redis Cluster Config Options</h3><p>Before we move ahead to setup the Redis Cluster, let’s get familiar with the config options for Redis Cluster.</p><p>You can find the config file in etc/redis/redis.conf file.</p><p><strong>A. cluster-enabled {yes/no}</strong></p><ul><li>Determines whether to run Redis in Cluster mode.</li></ul><p><strong>B. cluster-config-file {filename}</strong></p><ul><li>A config file managed by Redis Cluster for Cluster information. It is not modified by user.</li></ul><p><strong>C. cluster-node-timeout {milliseconds}</strong></p><ul><li>The time window after which a node is judged as behaving abnormal.</li><li>No write requests will be accepted after this time window.</li></ul><p><strong>D. cluster-replica-validity-factor {factor/seconds}</strong></p><ul><li>If a replica did not communicate with master within a scrtain time frame, it will be prevented to be promoted as master in case of failover.</li><li><em>A </em>replica that has not communicated with the master for<em><br></em>(<em>cluster-node-timeout factor</em>) seconds is excluded from failover.</li><li><em>Formula -&gt; cluster-node-timeout (5 seconds)</em> factor (10 seconds)<br>A replica node that has not communicated with the master node for 50 seconds cannot be promoted to a master node.</li><li><strong>cluster-migration-barrier {count}</strong></li><li>Minimum number of replicas a master must maintain</li><li>Some replicas may be migrated to replicas of masters that do not have replicas, as long as this number is met.</li><li><strong>cluster-require-full-coverage : {yes/no}</strong></li><li>Whether to not accept write requests when some hash slots are not covered</li><li>If set to no, you can ensure that the remaining hash slots work even if some nodes fail and the corresponding hash slots do not work properly.</li><li><strong>cluster-allow-reads-when-down : {yes/no}</strong></li><li>Whether to allow read requests to be accepted even when the cluster is not in a healthy state.</li><li>This can be set to yes if consistency of read operations is not important in your application.</li></ul><h3>A. Infrastructure Setup With Pulumi</h3><h4>A. Configure AWS CLI</h4><p>To ensure Pulumi works without errors, we need to configure the AWS CLI by providing the necessary credentials —</p><ul><li>AWS access key</li><li>Secret access key</li><li>Region (the region you want to deploy the setup)</li><li>Output format etc.</li></ul><p>Run the following command and follow the prompts:</p><pre>aws configure</pre><p>When prompted for the AWS access key and AWS secret access key, provide the access keys of the IAM role you created with full EC2 access.</p><h4>B. Pulumi Project Setup</h4><p>Since we have created and set up the necessary AWS credentials on our local machine, let’s create the Pulumi project. As we’ll test the Cluster with a Python-based project (<a href="https://www.djangoproject.com/">Django</a>), we’ll create a AWS environment with <a href="https://www.pulumi.com/docs/iac/get-started/aws/">Python-based Pulumi</a> project.</p><p><strong>i. Create a new directory and Navigate into IT</strong></p><pre># create directory and cd into it<br>mkdir my-redis-pulumi &amp;&amp; cd my-redis-pulumi</pre><p><strong>ii. Create an AWS-Python Pulumi Project</strong></p><pre>#create AWS-Python Pulumi project<br>pulumi new aws-python</pre><p>The commands will create an empty directory, cd into it and with the help of pulumicommand, a basic python based Pulumi project will be created.</p><p>When you run pulumi new aws-python, Pulumi will ask for an access token. Follow these steps —</p><ul><li><strong><em>Copy the URL displayed to generate an access token.</em></strong></li><li><strong><em>Log in to your Pulumi account and create the token.</em></strong></li><li><strong><em>Paste the token into the command prompt.</em></strong></li></ul><p>When prompted for the project environment, provide dev as the environment since we are not part of any organization. The remaining steps are straightforward—just follow along and provide any necessary credentials as prompted.</p><h4>C. Create AWS EC2 Key Pair</h4><p>We’ll now create <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">key-pair</a> for the instances to <a href="https://www.cloudflare.com/learning/access-management/what-is-ssh/">ssh</a> into them. Run the following command —</p><pre># creating a key-pair with the name of MyRedisClusterKeyPair.pem<br>aws ec2 create-key-pair - key-name MyRedisClusterKeyPair - query &#39;KeyMaterial&#39; - output text &gt; MyRedisClusterKeyPair.pem</pre><p>Set the correct permission to the key file —</p><pre>chomod 400 MyRedisClusterKeyPair.pem</pre><h4>D. Pulumi Script</h4><p>The following Pulumi script provisions the following resources in AWS —</p><ul><li><strong>A VPC</strong> with <strong>CIDR</strong> 10.0.0.0/16</li><li><strong>Three subnets</strong> in three <strong>different Availability Zones</strong> (AZs) with CIDR 10.0.1.0/24, 10.0.2.0/24, 10.0.3.0/24.</li><li>The Django app instance is created in ap-southeast-1a AZ, and the Redis Cluster instances are created in ap-southeast-1b and ap-southeast-1c — 3 instances per AZ.</li><li>One <strong>Internet Gateway</strong> (IGW).</li><li><strong>One Route Table</strong> and a route through the IGW.</li><li><strong>A Security Group</strong> that opens the following ports: 22for <strong>ssh</strong>, 8000 for <strong>Django App</strong>, 6379 for <strong>Redis client</strong>, and 16379 for <strong>Redis Cluster Bus communication</strong>.</li></ul><blockquote>NOTE 01: The Redis Cluster will <strong>only accept inbound traffic from </strong><strong>10.0.0.0/16</strong>, restricting access to the internal VPC network.</blockquote><blockquote>NOTE 02: If you’re not familiar with AWS basics such as VPCs, Subnets, and Security Groups, I recommend reading my <strong>AWS-101</strong> blog <a href="https://imehboob.medium.com/aws-networking-101-by-deploying-a-bastion-server-for-dummies-5458cd3a97b6"><strong>here</strong></a> get a solid understanding of the core AWS building blocks.</blockquote><p>Copy and paste the following Pulumi Python script into the __main__.py file in your Pulumi project.</p><pre>import pulumi<br>import pulumi_aws as aws<br><br><br>&#39;&#39;&#39;<br>Explanation: <br><br>The below script creates the following resources: <br><br>i. A VPC with CIDR 10.0.0.0/16 <br><br>ii. Subnets <br>    i. Three public Subnets <br>    ii. CIDRs of each subnets 10.0.1.0/24, 10.0.2.0/24, 10.0.3.0/24 <br><br>iii. One Internet Gateway<br><br>iv. One Route Table <br><br>v. Security Group <br>    i. Open Ports--<br>        i. 22 for SSH inbound traffic from 0.0.0.0<br>        ii. 8000 for Django app inbound traffic from 0.0.0.0 <br>        <br>        iii. 6379 for Redis clinet inbound traffic from 10.0.0.0/16<br>        iv. 16379 for Redis Cluster Bus inbound traffic from 10.0.0.0/16 <br><br><br>vi. EC2 Instance<br>    i. Instance Type: t2.micro <br>    ii. Instance Image: Ubuntu 24.04 LTS <br>    <br>    iii. Six EC2 Instances for Redis Cluster <br>    iv. One EC2 Instances for Django app. <br><br>&#39;&#39;&#39;<br><br># vpc <br>vpc = aws.ec2.Vpc(&quot;redis-vpc&quot;,<br>    cidr_block=&quot;10.0.0.0/16&quot;,<br>    enable_dns_hostnames=True,<br>    enable_dns_support=True,<br>    tags={<br>        &quot;Name&quot;: &quot;redis-vpc&quot;,<br>    }<br>)<br>pulumi.export(&quot;vpcId&quot;, vpc.id)<br><br># public subnets in three azs <br><br># subnet 01<br>public_subnet1 = aws.ec2.Subnet(&quot;subnet-1&quot;,<br>    vpc_id=vpc.id,<br>    cidr_block=&quot;10.0.1.0/24&quot;,<br>    availability_zone=&quot;ap-southeast-1a&quot;,<br>    map_public_ip_on_launch=True,<br>    tags={<br>        &quot;Name&quot;: &quot;subnet-1&quot;,<br>    }<br>)<br>pulumi.export(&quot;publicSubnet1Id&quot;, public_subnet1.id)<br><br># subnet 02<br>public_subnet2 = aws.ec2.Subnet(&quot;subnet-2&quot;,<br>    vpc_id=vpc.id,<br>    cidr_block=&quot;10.0.2.0/24&quot;,<br>    availability_zone=&quot;ap-southeast-1b&quot;,<br>    map_public_ip_on_launch=True,<br>    tags={<br>        &quot;Name&quot;: &quot;subnet-2&quot;,<br>    }<br>)<br>pulumi.export(&quot;publicSubnet2Id&quot;, public_subnet2.id)<br><br># subnet 03<br>public_subnet3 = aws.ec2.Subnet(&quot;subnet-3&quot;,<br>    vpc_id=vpc.id,<br>    cidr_block=&quot;10.0.3.0/24&quot;,<br>    availability_zone=&quot;ap-southeast-1c&quot;,<br>    map_public_ip_on_launch=True,<br>    tags={<br>        &quot;Name&quot;: &quot;subnet-3&quot;,<br>    }<br>)<br>pulumi.export(&quot;publicSubnet3Id&quot;, public_subnet3.id)<br><br><br># IGW (internet gateway)<br>internet_gateway = aws.ec2.InternetGateway(&quot;redis-igw&quot;,<br>    vpc_id=vpc.id,<br>    tags={<br>        &quot;Name&quot;: &quot;redis-igw&quot;,<br>    }<br>)<br>pulumi.export(&quot;igwId&quot;, internet_gateway.id)<br><br><br># Route Table<br>public_route_table = aws.ec2.RouteTable(&quot;redis-rt&quot;,<br>    vpc_id=vpc.id,<br>    tags={<br>        &quot;Name&quot;: &quot;redis-rt&quot;,<br>    }<br>)<br>pulumi.export(&quot;publicRouteTableId&quot;, public_route_table.id)<br><br><br># add route in the route table for the IGW<br>route = aws.ec2.Route(&quot;igw-route&quot;,<br>    route_table_id=public_route_table.id,<br>    destination_cidr_block=&quot;0.0.0.0/0&quot;,<br>    gateway_id=internet_gateway.id,<br>)<br><br># associate route tble with public subnets<br>rt_association1 = aws.ec2.RouteTableAssociation(&quot;rt-association-1&quot;,<br>    subnet_id=public_subnet1.id,<br>    route_table_id=public_route_table.id,<br>)<br>rt_association2 = aws.ec2.RouteTableAssociation(&quot;rt-association-2&quot;,<br>    subnet_id=public_subnet2.id,<br>    route_table_id=public_route_table.id,<br>)<br>rt_association3 = aws.ec2.RouteTableAssociation(&quot;rt-association-3&quot;,<br>    subnet_id=public_subnet3.id,<br>    route_table_id=public_route_table.id,<br>)<br><br># security group for django and Redis Instances<br>redis_security_group = aws.ec2.SecurityGroup(&quot;redis-secgrp&quot;,<br>    vpc_id=vpc.id,<br>    description=&quot;Allow SSH, Redis, and Node.js traffic&quot;,<br>    ingress=[<br>        {&quot;protocol&quot;: &quot;tcp&quot;, &quot;from_port&quot;: 22, &quot;to_port&quot;: 22, &quot;cidr_blocks&quot;: [&quot;0.0.0.0/0&quot;]},  # SSH<br>        {&quot;protocol&quot;: &quot;tcp&quot;, &quot;from_port&quot;: 6379, &quot;to_port&quot;: 6379, &quot;cidr_blocks&quot;: [&quot;10.0.0.0/16&quot;]},  # Redis<br>        {&quot;protocol&quot;: &quot;tcp&quot;, &quot;from_port&quot;: 16379, &quot;to_port&quot;: 16379, &quot;cidr_blocks&quot;: [&quot;10.0.0.0/16&quot;]},  # Redis Cluster<br>        {&quot;protocol&quot;: &quot;tcp&quot;, &quot;from_port&quot;: 8000, &quot;to_port&quot;: 8000, &quot;cidr_blocks&quot;: [&quot;0.0.0.0/0&quot;]},  <br>    ],<br>    egress=[<br>        {&quot;protocol&quot;: &quot;-1&quot;, &quot;from_port&quot;: 0, &quot;to_port&quot;: 0, &quot;cidr_blocks&quot;: [&quot;0.0.0.0/0&quot;]},  # Allow all outbound traffic<br>    ],<br>    tags={<br>        &quot;Name&quot;: &quot;redis-secgrp&quot;,<br>    }<br>)<br>pulumi.export(&quot;redisSecurityGroupId&quot;, redis_security_group.id)<br><br><br># AMI (amazon machine iamge) for the EC2 instances<br>ami_id = &quot;ami-01811d4912b4ccb26&quot;  # Ubuntu 24.04 LTS<br><br><br># create Instance for the django app in the first subnet (ap-southeast-1a)<br>django_app_instance = aws.ec2.Instance(&quot;django-app-instance&quot;,<br>    instance_type=&quot;t2.micro&quot;,<br>    vpc_security_group_ids=[redis_security_group.id],<br>    ami=ami_id,<br>    subnet_id=public_subnet1.id,<br>    key_name=&quot;MyRedisClusterKeyPair&quot;,  # NOTEe: Update your key pair if you have created keypair with dofferent name <br>    associate_public_ip_address=True,  <br>    tags={<br>        &quot;Name&quot;: &quot;django-app-instance&quot;,<br>        &quot;Environment&quot;: &quot;Development&quot;,<br>        &quot;Project&quot;: &quot;RedisClusterSetup&quot;,<br>    }<br>)<br>pulumi.export(&quot;djangoAppInstance&quot;, django_app_instance.id)<br>pulumi.export(&quot;djangoAppInstancePublicIp&quot;, django_app_instance.public_ip)<br><br><br># helper function to create otehr Redis instances<br>def create_redis_instance(name, subnet_id):<br>    return aws.ec2.Instance(name,<br>        instance_type=&quot;t2.micro&quot;,<br>        vpc_security_group_ids=[redis_security_group.id],<br>        ami=ami_id,<br>        subnet_id=subnet_id,<br>        key_name=&quot;MyRedisClusterKeyPair&quot;,  # NOTE: Update your key pair if you have created keypair with dofferent name <br>        associate_public_ip_address=True,<br>        tags={<br>            &quot;Name&quot;: name,<br>            &quot;Environment&quot;: &quot;Development&quot;,<br>            &quot;Project&quot;: &quot;RedisClusterSetup&quot;,<br>        }<br>    )<br><br># create Redis Cluster Instances across the remaining two subnets (Redis Cluster remains in the Subnet b and c)<br>redis_instance1 = create_redis_instance(&quot;redis-instance-1&quot;, public_subnet2.id)<br>redis_instance2 = create_redis_instance(&quot;redis-instance-2&quot;, public_subnet2.id)<br>redis_instance3 = create_redis_instance(&quot;redis-instance-3&quot;, public_subnet2.id)<br>redis_instance4 = create_redis_instance(&quot;redis-instance-4&quot;, public_subnet3.id)<br>redis_instance5 = create_redis_instance(&quot;redis-instance-5&quot;, public_subnet3.id)<br>redis_instance6 = create_redis_instance(&quot;redis-instance-6&quot;, public_subnet3.id)<br><br># cxporting Redis instance IDs and public IPs<br>pulumi.export(&quot;redisInstance1Id&quot;, redis_instance1.id)<br>pulumi.export(&quot;redisInstance1PublicIp&quot;, redis_instance1.public_ip)<br>pulumi.export(&quot;redisInstance2Id&quot;, redis_instance2.id)<br>pulumi.export(&quot;redisInstance2PublicIp&quot;, redis_instance2.public_ip)<br>pulumi.export(&quot;redisInstance3Id&quot;, redis_instance3.id)<br>pulumi.export(&quot;redisInstance3PublicIp&quot;, redis_instance3.public_ip)<br>pulumi.export(&quot;redisInstance4Id&quot;, redis_instance4.id)<br>pulumi.export(&quot;redisInstance4PublicIp&quot;, redis_instance4.public_ip)<br>pulumi.export(&quot;redisInstance5Id&quot;, redis_instance5.id)<br>pulumi.export(&quot;redisInstance5PublicIp&quot;, redis_instance5.public_ip)<br>pulumi.export(&quot;redisInstance6Id&quot;, redis_instance6.id)<br>pulumi.export(&quot;redisInstance6PublicIp&quot;, redis_instance6.public_ip)</pre><p>Run the following command to execute the Pulumi script —</p><pre>pulumi up </pre><p>If everything is configured correctly, you’ll see a message from Pulumi indicating that <strong>19 resources have been created</strong>, similar to the output below.</p><p>This is the power of <strong>IaC</strong> (Infrastructure as Code) platforms like Pulumi — automating repetitive tasks in the cloud environment. Once the script is executed successfully, log in to your AWS account to verify that the entire setup is ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*W65KK4ZCWCYsdzy_eBC8eg.png" /><figcaption>Pulumi Up command</figcaption></figure><h3>B. Redis Cluster Setup</h3><p>Since we’ve successfully provisioned the AWS environment, let’s install Redis on the instances for Cluster setup. We will <strong>SSH</strong> into each EC2 instance <strong>individually</strong> to install Redis and modify the configuration file.</p><p>In real-world practices, <strong>automation tools like Jenkins are often used to automate these tasks</strong> and prepare the resources. However, since using <strong>Jenkins is beyond the scope of this tutorial</strong>, <strong>we’ll manually SSH into each instance</strong> and perform the necessary steps.</p><h4>A. Collect Public and Private IPs</h4><p>To SSH into the instances, we need the <strong>public IPs</strong> of the instances.</p><p>Log into your AWS account and copy the <strong>public IPs</strong> and <strong>private IPs</strong> of all seven instances we provisioned.</p><ul><li>We need the <strong>public IP</strong> to SSH into the instances.</li><li>The <strong>private IP</strong> is required to set up the Redis Cluster, as Redis Cluster communicates over private IPs.</li></ul><h4>B. Install Redis</h4><p>We’ll ssh to each six Redis instances one by one, and do the following.</p><blockquote>NOTE: You have to manually ssh to all the six Redis instances and perform the following changes to each instances.</blockquote><p><strong>i. ssh to Intance</strong></p><pre>ssh -i /absolute/path/to/MyRedisClusterKeyPair.pem/file ubuntu@&lt;instance-public-ip&gt;</pre><p><strong>ii. Update the system</strong></p><pre># update <br>sudo apt update </pre><p><strong>iii. Install Redis</strong></p><pre>sudo apt install redis-server -y </pre><p><strong>iv. Start and Enable Redis Service</strong></p><pre># start redis service <br>sudo systemctl start redis-server<br><br>#enable redis service auto startup at reboot <br>sudo systemctl enable redis-server</pre><p><strong>v. Verify Redis is Running</strong></p><pre>sudo systemctl status redis-server</pre><h4>C. Edit redis.conf File for Cluster</h4><p>Since Redis installation is complete, and Redis is running, let’s configure the redis.conffile to setup Cluster. Currently Redis is running as Single Node Redis.</p><p><strong>i. Opne the redis.conf file</strong></p><pre>sudo nano /etc/redis/redis.conf</pre><p><strong>ii. Enable the Settings</strong></p><p>Copy and paste the below settings anywhere in the file and save it. I have already described the config options meaning, still there are few config that I have not touched. <strong>You can take this as your homework to learn more about rest of the configs.</strong></p><blockquote>a. Find the bind 127.0.0.1 -::1 and replace it with the below —</blockquote><pre>bind 0.0.0.0</pre><blockquote>b. Find the protected-mode yes and replace it with the below —</blockquote><pre>protected-mode no</pre><blockquote>c. Find the appendonly no and replace it with the below —</blockquote><pre>appendonly yes</pre><blockquote>d. Finally, copy and paste the below settings anywhere in the file —</blockquote><pre>cluster-enabled yes<br><br>cluster-config-file nodes.conf<br><br>cluster-node-timeout 15000</pre><p><strong>iv. Restart Redis</strong></p><p>Save and exit the file, and restart Redis —</p><pre>sudo systemctl restart redis-server</pre><h4>D. Create the Redis Cluster</h4><p>Once you’ve ssh into all the six instances, edit the config file as shown above, let’s setup the Cluster now.</p><p><strong>i. Install Redis CLI Tool</strong></p><p>SSH into any Redis instance and install Redis CLI tool to configure the Cluster.</p><pre>sudo apt update<br>sudo apt install redis-tools -y </pre><p><strong>ii. Create the Redis Cluster</strong></p><p>You’ll need the EC2 instance’s private IP address at this time. I hope you’ve already copied them from previous steps.</p><p>Edit the below command by replacing the private IP of the instances and run the command in the Redis instance where you’ve installed the Redis CLI tool.</p><pre>redis-cli --cluster create \<br>&lt;redis-instance-1-privateIP&gt;:6379 &lt;redis-instance-2-privateIP&gt;:6379 \<br>&lt;redis-instance-3-privateIP&gt;:6379 &lt;redis-instance-4-privateIP&gt;:6379 \<br>&lt;redis-instance-5-privateIP&gt;:6379 &lt;redis-instance-6-privateIP&gt;:6379 \<br>--cluster-replicas 1</pre><p>The command initializes a Redis Cluster with six nodes (3 master and 3 replica nodes) across the specified private IP address and the ports. The --cluster-replicas 1 flag <strong>indicates that each primary node will have one replica node.</strong></p><p><strong>iii. Confirm the Cluster</strong></p><p>You’ll be prompted to confirm the Cluster by Redis. It will devide the hash slots with among the six nodes.</p><p><strong>iv. Successful Cluster Creation</strong></p><p>By this time you’ll have successfully create the Redis Cluster.</p><h3>C. Setup Django App</h3><p>I’ll test the Cluster with a Django app but you can test it with any framework you’d like.</p><h4>A. SSH into EC2</h4><p>SSH into the additional EC2 instance we’ve created for our application to test the Cluster.</p><pre>ssh -i /absolute/path/to/MyRedisClusterKeyPair.pem/file ubuntu@&lt;instance-public-ip&gt;</pre><h4>A. Install Necessary Packages</h4><p>Run the following commands to setup the app environment.</p><pre># Create a directory and navigate into it<br>mkdir mydjango &amp;&amp; cd mydjango<br><br># Update package lists<br>sudo apt update<br><br># Install Python 3 and pip<br>sudo apt install python3 python3-pip python3-distutils -y<br><br># Verify Python 3 and pip installation<br>python3 --version<br>pip3 --version<br><br># Install python3-venv<br>sudo apt-get install python3-venv<br><br># Create a virtual environment <br>python3 -m venv venv<br><br># Activate the virtual environment<br>. venv/bin/activate<br><br># Upgrade pip within the virtual environment <br>python3 -m pip install --upgrade pip<br><br># Install Django 4.2.2<br>pip install Django==4.2.2<br><br># Verify Django installation<br>python3 -m django --version<br></pre><h4>C. Setup Django App</h4><p>Follow the below commands to setup the Django app —</p><pre># Activate the virtual environemt<br><br># Create a Django project named &quot;my-redis-cluster&quot;<br>django-admin startproject my_redis_cluster <br><br># Navigate into the project directory<br>cd my_redis_cluster<br><br># Create a Django app named &quot;my_app&quot;<br>python3 manage.py startapp my_app<br><br># Add &quot;my_app&quot; to the INSTALLED_APPS list in settings.py<br># Open my_redis_cluster/settings.py in a text editor <br>nano my_redis_cluster/settings.py<br><br># Add &#39;my_app&#39; to the INSTALLED_APPS list:<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;my_app&#39;,  # Add this line<br>]<br><br># Save and close the file.<br><br># Update the main urls.py file (my_redis_cluster/urls.py)<br>nano my_redis_cluster/urls.py<br><br># Replace the existing code with the following:<br><br>from django.contrib import admin<br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, include(&#39;my_app.urls&#39;)), #Include my_app urls<br>]<br><br># Save and close the file.<br><br># Create a urls.py file in the &quot;my_app&quot; directory<br>nano my_app/urls.py<br><br># Add the following code:<br><br>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>    path(&#39;&#39;, home, name=&#39;home&#39;),<br>    path(&#39;set/&#39;, SetValueView.as_view(), name=&#39;set_value&#39;),<br>    path(&#39;get/&lt;str:key&gt;/&#39;, GetValueView.as_view(), name=&#39;get_value&#39;),<br>]<br># Save and close the file.<br></pre><h4>D. Setup the Django views.py File</h4><p>Update the my_app/view.py file with the below code —</p><blockquote>NOTE: You must update the startup_nodes with the Redis EC2 instances private IP below —</blockquote><pre>startup_nodes = [<br>    {&quot;host&quot;: &quot;redis1-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis2-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis3-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis4-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis5-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis6-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>]</pre><pre># my_app/views.py<br><br>from django.http import JsonResponse<br>from django.views import View<br>from django.urls import path<br>from django.utils.decorators import method_decorator<br>from django.views.decorators.csrf import csrf_exempt<br>from rediscluster import RedisCluster<br>import json<br><br># Redis Cluster configuration<br>startup_nodes = [<br>    {&quot;host&quot;: &quot;redis1-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis2-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis3-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis4-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis5-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>    {&quot;host&quot;: &quot;redis6-instance-private-ip&quot;, &quot;port&quot;: &quot;6379&quot;},<br>]<br><br># initializing the Redis Cluster<br>redis_cluster = RedisCluster(startup_nodes=startup_nodes, decode_responses=True)<br><br># main route to confirm server is running<br>def home(request):<br>    return JsonResponse({&quot;message&quot;: &quot;Django server is running!&quot;})<br><br># set key-value in Redis Cluster<br>@method_decorator(csrf_exempt, name=&#39;dispatch&#39;)<br>class SetValueView(View):<br>    def post(self, request):<br>        try:<br>            data = json.loads(request.body)<br>            key = data.get(&quot;key&quot;)<br>            value = data.get(&quot;value&quot;)<br>            if not key or not value:<br>                return JsonResponse({&quot;error&quot;: &quot;Key and value are required&quot;}, status=400)<br>            redis_cluster.set(key, value)<br>            return JsonResponse({&quot;message&quot;: &quot;Value set successfully&quot;})<br>        except Exception as e:<br>            return JsonResponse({&quot;error&quot;: str(e)}, status=500)<br><br># get value from Redis Cluster<br>class GetValueView(View):<br>    def get(self, request, key):<br>        try:<br>            value = redis_cluster.get(key)<br>            if value is None:<br>                return JsonResponse({&quot;message&quot;: &quot;Key not found&quot;}, status=404)<br>            return JsonResponse({key: value})<br>        except Exception as e:<br>            return JsonResponse({&quot;error&quot;: str(e)}, status=500)<br></pre><h4>E. Run Django Server</h4><p>Run and access the server by following the below command.</p><pre># Run migrations (although there are no models yet, but it&#39;s good practice)<br>python3 manage.py migrate<br><br># Run the development server<br>python3 manage.py runserver 0.0.0.0:8000<br><br># Access your Django app in a web browser using your EC2 instance&#39;s public IP address or public DNS name:<br># http://&lt;your_ec2_public_ip&gt;:8000/set/<br># http://&lt;your_ec2_public_ip&gt;:8000/get/<br># http://&lt;your_ec2_public_ip_or_dns&gt;:8000/</pre><h4>F. Save Data in Cluster</h4><p>A simple script to save data in the Cluster.</p><pre># set_data.py <br><br>import requests<br><br>url = &quot;http://&lt;your_ec2_public_ip&gt;:8000/set/&quot;<br>data = {<br>    &quot;key&quot;: &quot;myKey&quot;,<br>    &quot;value&quot;: &quot;myValue&quot;<br>}<br><br>resp = requests.post(url, json=data)<br><br># print raw response<br>print(f&quot;Status Code: {resp.status_code}&quot;)<br>print(f&quot;Response Text: {resp.text}&quot;)<br><br># only parse JSON if response is valid<br>try:<br>    print(resp.json())<br>except requests.exceptions.JSONDecodeError:<br>    print(&quot;Response is not valid JSON.&quot;)<br><br><br># You can also use CURL for the same<br>curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;key&quot;: &quot;myKey&quot;, &quot;value&quot;: &quot;myValue&quot;}&#39; http://your_ec2_public_ip:8000/set/</pre><h4>G. Get Data from Cluster</h4><p>A simple script to get data from the Cluster.</p><pre># get_data.py<br><br>import requests<br><br>url = &quot;http://&lt;your_ec2_public_ip&gt;:8000/get/key-name&quot;<br><br>response = requests.get(url)<br><br>if response.status_code == 200:<br>    print(&quot;Response:&quot;, response.json())  <br>else:<br>    print(&quot;Error:&quot;, response.status_code, response.text)<br><br># You can also use CURL to get the data<br>curl -X GET &quot;http://your_ec2_public_ip:8000/get/key-name&quot;</pre><h4>H. Test Cluster via the Redis CLI</h4><p>SSH into any EC2 Redis EC2 instance and connet to the Redis CLI using the following command —</p><pre>redis-cli -c -h &lt;redis-node-private-ip&gt; -p 6379</pre><p>Now try to set and get any value using set and get command. You will be redirected to the specific node that has saved the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*B30fz--mPcC0PQFCie0_Tw.png" /><figcaption>Redis Cluster</figcaption></figure><p>However, in case of actual client, this redirection will not happen as real clients maps the hash slots and the node address in them.</p><blockquote><a href="https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/">The </a><a href="https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/">redis-cli cluster support is very basic</a>, so it always uses the fact that Redis Cluster nodes are able to redirect a client to the right node. A serious client is able to do better than that, and cache the map between hash slots and nodes addresses, to directly use the right connection to the right node. The map is refreshed only when something changed in the cluster configuration, for example after a failover or after the system administrator changed the cluster layout by adding or removing nodes.</blockquote><h3>Learning Outcome</h3><p>In this tutorial, we —</p><ul><li><strong>Introduced Pulumi and the concept of IaC.</strong></li><li><strong>Set up AWS infrastructure using Pulumi.</strong></li><li><strong>Provisioned a VPC, three subnets, seven EC2 instances across different subnets, Security Groups, a Route Table, and an Internet Gateway.</strong></li><li><strong>Installed Redis on EC2 instances via SSH.</strong></li><li><strong>Configured a Redis Cluster on six instances.</strong></li><li><strong>Set up a Django app on another EC2 instance.</strong></li><li><strong>Tested the Cluster using the Django app to set and retrieve data.</strong></li><li><strong>Verified the Cluster setup using the Redis CLI.</strong></li></ul><h3>Summary</h3><p><a href="https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b">The first part</a> of this tutorial focused on the <strong>theoretical knowledge of Redis single-node and multi-node deployments, highlighting Redis Replication, Sentinel, and Cluster with their use cases</strong>.</p><p>In this tutorial, <strong>we explored Pulumi as an IaC platform, provisioned AWS infrastructure using Pulumi, and set up a Redis Cluster along with a Django app to test the Cluster</strong>.</p><p>I hope this hands-on tutorial helped you understand the steps involved in setting up a basic Redis Cluster.</p><p>In the upcoming tutorial, we’ll design a more robust AWS infrastructure with —</p><ul><li><strong>Production-grade security (though the current setup is quite secure).</strong></li><li><strong>Automation using Jenkins.</strong></li><li><strong>A more resilient Redis Cluster.</strong></li></ul><p>Till then, keep pushing, keep learning — peace!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d96afdb2b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Easy Guide to Design Highly Available System with Redis | Part 1]]></title>
            <link>https://imehboob.medium.com/your-easy-guide-to-design-highly-available-system-with-redis-part-1-812d3baec45b?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/812d3baec45b</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[high-availability]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 18:58:55 GMT</pubDate>
            <atom:updated>2025-05-03T16:24:18.092Z</atom:updated>
            <content:encoded><![CDATA[<h4>Highly Available System with Redis Cluster for Dummies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*ATnOiR9TIVzHPiqj631IgQ.png" /></figure><h3>Table of Contents</h3><ul><li>Introduction</li><li>Intended Audience</li><li>Learning Structure</li><li>Mode of Learning</li><li>Outcome of Learning</li><li>Single Node Redis</li><li>Multi Node Redis</li><li>Replication</li><li>Sentinel</li><li>Cluster</li><li>Summary</li><li>Part 2</li></ul><h3>Intended Audience, Learning Structure, Mode of Learning</h3><p>Well, anyone. If you’re just curious on a weekend to learn in-depth about Redis Multi Node setup, their pros and cons, and something about everything related to Redis HA (High Availability), you’re welcome.</p><h3>Introduction</h3><p>Well, Redis. You must be thinking about caching when you read Redis by this time. Well, Redis is much more than just caching. I assume you have some basic understanding of why we’d use Redis other than for caching.</p><p>We’d not explore the use cases of Redis here, but we’d be doing something more exciting in this blog series — <strong><em>Scaling Redis!</em></strong></p><p>There are two ways to deploy Redis —</p><ul><li><strong>Single-node deployment.</strong></li><li><strong>Multi-node deployment.</strong></li></ul><p>We’ll explore the —</p><ul><li><strong>limitations of single-node deployment.</strong></li><li><strong>when to use single-node Redis.</strong></li><li><strong>how to scale Redis with multi-node deployment.</strong></li></ul><p>We’ll also cover —</p><ul><li><strong>the types of multi-node deployments.</strong></li><li><strong>and their use cases.</strong></li></ul><p>Cool. Let’s go!</p><h3>Single Node Redis</h3><p>In single-node Redis, as the title suggests, you have only one Redis instance. This mean —</p><ul><li>all the writes and reads happen on a single machine.</li></ul><h4>Use Cases of Single Node Redis</h4><p>You’d want to use single-node Redis deployment in cases when —</p><ul><li><strong>the system is not read/write heavy.</strong></li><li><strong>it’s handling offloaded tasks.</strong></li><li><strong>the system is relatively small.</strong></li><li><strong>it does not demand exceptional throughput.</strong></li><li><strong>you do not need HA (High Availability) or replica.</strong></li></ul><h4>Difficulties with Single Node Redis</h4><p><strong>A. Availability</strong>:</p><p>As you are running Redis in a single instance, it is prone to Single Point of Failure (<strong>SPOF</strong>). If the instance fails due to extraordinary events, network failure, or other unforeseen circumstances, your system may suffer.</p><p><strong>B. Scalability in terms of Data Storage</strong>:</p><p>When you have a single Redis instance, you are limited to vertical scaling. Your data must fit within the capacity of the highest possible level of vertical scaling of the instance.</p><p><strong>C. Scalability in terms of TPS (Transaction per Seconds)</strong>:</p><p>A single instance is bound by limited resources such as CPU and RAM. If your read/write operations exceed the limits of the instance, Redis may crash.</p><p>If you encounter any of the issues listed above, you need to scale your Redis setup to a<strong> multi-node deployment</strong>. There are mainly three types of multi-node deployments available with Redis —</p><ul><li><strong>Replication</strong></li><li><strong>Sentinel</strong></li><li><strong>Cluster</strong></li></ul><p>Let’s address them one by one.</p><h3>Redis Multi Node Deployment — Replication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*KXgwKKw9Mhpf4CthAqO67w.png" /><figcaption>Redis master-slave architecture</figcaption></figure><p>The Redis Replication architechture is straight forward. It has a <strong>master</strong> node and a few <strong>slave/replica</strong> nodes.</p><p>The master node handles <strong>all the writes</strong>, and occasionally, in some cases, if configured, some reads.</p><p>The slave/replica nodes are responsible for <strong>all the reads</strong> and <strong>no writes</strong>.</p><h4><strong>Benefits of Replication: Distributed Processing</strong></h4><p>Redis replication is <strong>weak consistency</strong>. Data written by the master node is asynchronously replicated/distributed to all the slave/replica nodes.</p><p>In simple terms, the master does not wait for all the replicas to let them write the data into their environment before sending <strong>acknowledgement</strong> to the client.</p><p><strong>A. Strong Consistency</strong>: In case of strong consistency, the node will make sure all the replicas have the same data and no stale data. Strong consistency causes severe performance degredation.</p><p><strong>a. Master Data Write</strong> -&gt; b. <strong>Replication Process</strong> <strong>to Replicas</strong> -&gt; <strong>ACK Signal sent.</strong></p><p><strong>B. Redis Weak Consistency</strong>: In terms of Redis —</p><p><strong>b. Master Data Write</strong> -&gt; b. <strong>ACK Signal sent</strong> -&gt; c. <strong>Replication Process to Replicas.</strong></p><h4>Benefits of Replication: Faster Read</h4><p>As the responsibility is distributed into <strong>master</strong> and <strong>replica </strong>nodes, and as there are generally more than one master node, the read operation is faster than <strong>Single Node Redis</strong> environment.</p><h4>Problems with Replication</h4><p><strong>A. No Improvement in Write Speed</strong>:</p><p>As there is only one master node, and as the master node is only responsible for write in the architecture, there is <strong>no improvement in write speed</strong>. <strong>If your system is write heavy, Replication might not be a good choice.</strong></p><p><strong>B. No Data Sharding:</strong></p><p>All the replica nodes just copies the master node. Hence the data that is written by the master node, is also available in the replica nodes as a copy. <strong>Hence, there is no improvement in the amount of data that can be stored. The problem of Vertical Scaling of single Redis instance is still unsolved.</strong></p><p><strong>C. Write Single Point of Failure:</strong></p><p>As write happens only through a single master node, if the node fails, all write requests will eventually fail. This may continue to serve the all the reads, but the system may be corrupt with dirty read.</p><p><strong>D. No High Availability:</strong></p><p>Replication in Redis does not have any automatic failover mechanism. In cases of system failure, a manual intervention is required. You manually need to connect to the instance and promote new master in cases of failure. Hence, Replication does not gurantee high availability.</p><h4>Use Cases of Replication</h4><p>You’d want to use Replication in cases when —</p><ul><li>you have read heave application.</li><li>you do not need HA.</li><li>you want faster read.</li><li>you want multi-key operation.</li><li>your system is not write heave.</li><li>you want distributed architecture.</li></ul><h3>Redis Multi Node Deployment — Sentinel</h3><p><strong>In straightforward terms, Redis Sentinel is a wrapper on Redis Replication to achieve HA.</strong></p><p>You have Redis Replication set up. Replication does not come with automatic failover. To mitigate this problem, with the same setup of Replication, we can use Sentinel, an another multi node Redis deployment, for automatic failover to achieve high availability.</p><h4>Redis Sentinel — What Problem Does it Solve</h4><p>If you have Replication setup, and your use case if fulfilled with Replication, <strong>but you want to achieve High Availability in your system with single Master node</strong> — that is, if the master fails, the system should automatically heal and promote a new master to drive all the write to the new master without any manual intervention, then you’d want to use Redis Sentinel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*EdBcjruCsa8LGHokPAeAmw.png" /><figcaption>Redis Sentinel Architecture</figcaption></figure><blockquote>A. Redis Sentinel is a regular Redis Replication architecture. However, in Sentinel architecture, there are additional nodes named as “sentinel” that monitors, notifies, and performs failover to achieve high availability.</blockquote><blockquote>B. Sentinels are actually distinguished/separate servers/nodes.</blockquote><blockquote>C. Sentinel node can also fail, hence, it is always advised to have odd number of sentinel nodes.</blockquote><h4>How Redis Sentinel Works</h4><p>Let’s understand how Redis Sentinel works —</p><p><strong>A. Redis Replication:</strong></p><p>You have the general Redis Replication setup consisting one master node and a few replica nodes. The master handles write operations and the replicas handle read operations.</p><p><strong>B. Sentinel Instances/nodes:</strong></p><p>Redis Sentinels are separate process or collection of processes (to mitigate <strong>SPOF</strong> of single Sentinel process) running in separate instances.</p><p><strong>Sentinel primarily performs four kind of tasks:</strong></p><p><strong><em>a. Monitoring: </em></strong>Sentinel nodes continuously checks if the master node is available. Generally Sentinel nodes pings each second to the master node by default.</p><p><strong><em>b. Notification:</em> </strong>Sentinel can notify the administrators about the master node unavailability as per configuration.</p><p><strong><em>c. Leader Election: </em></strong>In cases of master node unavailability, all the sentinels performs an election and elect one Sentinel node as leader to perform the failover.</p><p><strong><em>d. Failover Detection and Orchestration: </em></strong>The Sentinels detects any unavailability of the master node, and if detected, a leader Sentinel node performs the failover and promotes one of the healthy replica (based on various metrices) to new master and orchestrates other replicas to read from new master.</p><p><strong>C. Failover Detection:</strong></p><p>Based on various configurations (e.x: down-after-milliseconds i.e. if the master is not reachable within this time frame), a Sentinel node flags the master as SUBJECTIVELY DOWN (SDOWN) state.</p><p><strong>D. Objective Down (ODOWN):</strong></p><p>A single Sentinel flag as master is down is not enough to roll out a failover. If the quorum of Sentinel instances ( quora=um is configurable number in sentinel.conf) agress that the master is down, then the master is considered as OBJECTIVELY DOWN (ODOWN).</p><p>The quorum is crucial in order to perform leader election and perform failover to mitigate “<strong>split-brain</strong>” problem where more than one Sentinel node independently try to failover leading to data inconsistency.</p><p><strong>E. Sentinel Leader Election:</strong></p><p>Once the master is identified with ODOWN state, all the Sentinel instances gets ready for an election to become a leader. The elected leader will then perform the actual failover of the master node. Redis Sentinel uses a simplified version of <a href="https://raft.github.io/">Raft Consensus Algorithm</a> for leader election.</p><p><strong>F. Replica Selection for Promotion:</strong></p><p>The elected Sentinel leader then selects one of the available and healthy replica to be promoted to the new master. The master selection criteria involves some crusical factors, such as —</p><ul><li><strong><em>Replica Priority: A </em></strong>configuration value to indicate the priority of becoming master. The lower value == higher priority. 0 value makes impossible for a replica to become master.</li><li><strong><em>Replication Offset:</em></strong> The replica that has the most up to date data i.e. highest replication offset gets higher priority.</li><li><strong><em>Connectivity:</em></strong> The replica that has made most successful health checks by Sentinel nodes.</li><li><strong><em>Process ID:</em></strong> In case of tie, the process ID of the replicas are choosen. The less, the higher priority.</li></ul><p><strong>G. Failover Execution:</strong></p><p>The elected Sentinel leader then performs the following actions to execute the failover:</p><ul><li>send a <a href="https://redis.io/learn/operate/redis-at-scale/high-availability/understanding-sentinels">SLAVEOF NO ONE</a> command to the choosen replica, promoting it to teh new master node.</li><li>instructs the other remaining replicas to start replicating from the new master.</li><li>Updates the internal configuration to reflect the new master.</li></ul><h4>Problems with Redis Sentinel</h4><p>As Sentinel only makes sure HA in a Redis Replication, <strong>hence the Vertical Scale of instance for data size fit issue is still not resolved</strong> as master node is only responsible for data write and all other replicas just copies the master node. <strong>Teh data is not sharded among the replicas.</strong></p><p><strong>However, Sentinel makes Replication highly available.</strong> <strong>If the data size is not an issue, and if a system only need be highly available, </strong>in such cases, Redis Sentinel is the answer.</p><h4>Use Cases of Sentinel</h4><p>As you’ve seen Sentinel is Replication with HA through automatic failover.</p><p><strong>If your service should be highly available, but the data storage limits are not factor,</strong> you should choose Redis Sentinel.</p><p><strong>If highly availability is crusial for you system,</strong> <strong>but you do not want to shard your Redis database,</strong> in such cases too you should opt for Redis Sentinel.</p><h3>Redis Multi Node Deployment — Cluster</h3><p>We have discussed in Redis Sentinel that Sentinel though provide HA but it does not provide horizontal scaling.</p><p>In simple terms, Redis Replication and Redis Sentinel only works with Single master node. In case with single master node, you are limited to the highest level of vertical scaling of the master node to fit in your Redis database.</p><ul><li><strong><em>What happens when we need more than one master node to actually scale horizontally so that we can utilize increased Redis database size?</em></strong></li><li><strong><em>What happens if our application is write heavy and a single master node is not capable of all the write throughput of our system?</em></strong></li><li><strong><em>What happens if we want to shard our Redis database in truly distributed system to decrease the load from single master Redis?</em></strong></li></ul><p>Redis Cluster is the solution to all the above problems described. In a typical Redis Cluster architecture, the minimal requirements are at least 3 master node, and at least 3 replica node — one for each master node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Jm0z0rT6t7trrwtuIWb8Tw.png" /><figcaption>Redis Cluster</figcaption></figure><p>The diagram shows a Redis Cluster setup with three master node and three replica nodes for each master nodes.</p><h4>So, What is Redis Cluster</h4><p>In simple terms, <strong>Redis Cluster is</strong> —</p><ul><li><strong>Automatic data distribution</strong> accross multiple replica nodes.</li><li><strong>Availability that continues to operate even when some node fails</strong>, or communication between internal nodes are disrupted.</li><li><strong>Architecture for horizontal scaling providing a smooth solution for data sharding </strong>and vertical scale issue in Redis Replication and Redis Sentinel.</li><li><strong>Provides high availability through gossip protocol</strong>.</li></ul><h4>Redis Cluster Features</h4><ul><li>Cluster communicates with <strong>full-mess structure</strong>.</li><li>Cluster uses an <strong>additional channel (port) for communication known as cluster bus.</strong></li><li>Masters use <a href="https://highscalability.com/gossip-protocol-explained/"><strong>gossip protocol</strong></a><strong> </strong>to stay connected.</li><li><strong>Data is distributed</strong> i.e. sharded into different nodes.</li><li>Key management happens using <strong>hashing</strong>.</li><li><strong>Only DB0 is available in Cluster</strong>.</li><li><strong>Multi-key operation is not executable</strong>.</li><li><strong>Highly available system</strong> with self healing.</li><li><strong>Suitable for write heavy system</strong>.</li></ul><h4>Redis Sentinel vs Redis Cluster</h4><ul><li>Redis Sentinel <strong>needs additional nodes</strong> (for sentinel service) for HA while <strong>Redis Cluster is self healing</strong> i.e. the Cluster itself can orchestrate a failover.</li><li>Redis Sentinel does not offer data sharding, while Cluster does.</li><li>Sentinel is adopted where HA is crucial but in small scale system, while Cluster is truly distributed HA architecture for large scale write heavy system.</li><li><strong>Sentinel allows multi-key operations as data is not sharded</strong>, whereas <strong>Cluster does not support multi-key operations as data is truly distributed</strong>.</li></ul><h4>Data Distribution</h4><p>All the write happens through all the available master nodes.</p><p><strong>Redis divides the key space into </strong><strong>16384 hash slots</strong> and distributes the slots with all the available nodes.</p><p><strong>Each key is hashed with </strong><a href="https://stackoverflow.com/questions/10564491/function-to-calculate-a-crc16-checksum"><strong>CRC 16</strong></a><strong> (Cyclic Redundancy Check — checksum algorithm)</strong> and then mapped to each hash slots by module operation with 16384.</p><h4>Data Consistency</h4><p><strong>Redis Cluster does not provide strong consistency, rather it provides eventual consistency</strong>.</p><p><strong>A. Weak Consistency in Redis Cluster</strong>:</p><p><em>a. Write Complete. → b. ACK. → c. Replication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*OT7Kx0cI4bL89EyIUsQ_xw.png" /><figcaption>Data consistency in Redis Cluster</figcaption></figure><h4>Cluster Performance</h4><p>Clients map the actual node address to hash slots to directly communicate with the required node. However, in some cases, there might be errors sush as MOVED, in that case, the client needs to re-request to the node.</p><p>Redis Cluster is designed to provide high performance and scalability while maintaining appropriate levels of data reliability and availability.</p><p><strong>However, Redis Cluster may fail in some extreme cases such as the majority of masters are not available to perform a failover.</strong></p><h4>Cluster Availability</h4><p><strong>Redis Cluster is self-healing</strong> i.e. Cluster itself detects failure and orchestrates failover without the need of any additional nodes.</p><p>Once a master detected as failure, and quorum reached, <strong>one of the replica of the master node is promoted as new master node.</strong></p><p>The hash slots covered by the previous master node will be covered by the newly promoted master node.</p><p>If a master fails to communicate with a majority of masters, and the node timeout exceeds, <strong>the master enters into an error state and does not accept any write requests.</strong></p><h4>Cluster Constraints</h4><p><strong>A. Only DB0 is Available in Cluster</strong></p><p>As Redis can have multiple database configured (<strong>default 16</strong>), in case of Cluster, the multi database is not available and it is fixed to <strong>db0 or database 0</strong>.</p><p><strong>B. Restrictions on Multi-Key Operations</strong></p><p>For a successful multi key operation, all the data should be available in same instance. As in Redis Cluster, data is sharted/distributed into different nodes, the multi-key operation (e.g. MSET ) is not available.</p><blockquote>NOTE: <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/">multi-key operatoin in Cluster is actually available in limited scope</a>. All the data must be in same hash slot for multi-key operation and multi-key ops is done with the help of hash tag in Cluster in limited scope.</blockquote><pre># Example of multi-key operation<br><br>mset {roll:1}:age 18 {roll:1}:class vi (possbile for identical hash tag) <br><br>mset user{101}:age 20 product{101}:price 100 (not possible for different tag)</pre><h4>Networking in Cluster</h4><p>Every Redis Cluster node requires two open TCP connection.</p><ul><li>The command port i.e. 6379 to serve the clients.</li><li>The cluster bus port — by default the cluster bus port is calculated by 10000 + command port i.e. 16379. The cluster port is configurable by overriding the cluster-port config.</li></ul><p>The Cluster bus is responsible for node-to-node communication. The client should never try to communicate through the cluster-bus port. <strong>Cluster uses the cluster-bus port for failure detection, configuration updates, failover orchestration etc.</strong></p><p>Hence, we need to open 6379 and 16379 both ports in our firewall config in order to allow Cluster work successfully.</p><p>However, in case of using Redis Cluster in <a href="https://www.docker.com/">Dockerized</a> environment, <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/">Cluster is not possible in NATed scope </a>i.e. in port forwarding scenarion. In such case, we need to use <a href="https://docs.docker.com/engine/network/">host network</a> of Dockerized environemnt in order to use Redis Cluster.</p><h4>Use Cases of Redis Cluster</h4><ul><li>When you want self-healing HA system.</li><li>If you need write heavy system with higher throughput.</li><li>If Vertical Scaling is not solving issue, and Linear Scaling is only solution.</li></ul><h3>Summary and Part 2</h3><p>We have discussed single node Redis to Redis Replication, Sentinel to Redis Cluster. In this introductory blog, we have only understood the theoritical knowledge of various Redis deployment, their use cases, and some of their internal workings.</p><p>In coming blog, we will deploy a Redis Cluster in <a href="https://aws.amazon.com/elasticache/redis/">AWS</a> environment. We’ll setup the infrastructure with <a href="https://www.pulumi.com/">Pulumi</a>, configure the <a href="https://redisson.pro/glossary/redis-cluster.html">Redis Cluster</a>, deploy an <a href="https://docs.djangoproject.com/en/5.1/intro/tutorial01/">Django</a> app in the AWS environment, and check whether our Redis Cluster is able serve the Django app with ease. Till then, keep hustling, keep pushing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=812d3baec45b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Minimal Life Cycle of a Docker Container]]></title>
            <link>https://imehboob.medium.com/the-minimal-life-cycle-of-a-docker-container-07e57f08a6a8?source=rss-e5c62f42f962------2</link>
            <guid isPermaLink="false">https://medium.com/p/07e57f08a6a8</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[The Backend Diaries]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 10:27:02 GMT</pubDate>
            <atom:updated>2025-03-22T10:27:02.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>A minimal life cycle overview of docker containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xU-JCTYzBe6sGqNd" /><figcaption>Photo by <a href="https://unsplash.com/@victoire_jonch?utm_source=medium&amp;utm_medium=referral">Victoire Joncheray</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this short blog, we will learn minimal life cycle of docker containers. We would learn about the cycle of create, exec, write, stop, restart and delete docker containers in this introductory post.</p><h3>Creating and Starting a Container</h3><p>To create a docker container, we would use the docker run command. Run the below command to create and start our first container.</p><pre>docker run -itd --name my-container-1 ubuntu:latest </pre><p>Let’s understand the command —</p><p>The docker run command creates and runs a docker container.</p><p>The -i means --interactive mode. This flag keeps the standard input ( stdin ) open even the host is not attached to the container.</p><p>The -t means --tty . This flag allocates a pseudo-TTY connectd to the container’’s stdin, stdout, and stderr. It is mainly responsible for the terminal-like interface within the container.</p><p>The -d means --detach mode. This flag runs the container in the background i.e. in detached mode. This means that after starting the container, docker will return you to your host machine’s command prompt. The container will continue to run in the background.</p><p>You can run a docker continaer without in -d mode but once you exit the container, it ceases to stop or you have to press CTRL PQ to exit the contianer without killing it.</p><p>The ubuntu:latest flag is the actual image we are running using the docker run command.</p><p>Once you run the container, you’d get an ID of the continaer returned by docker which indicates the container is running in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*CscemhzzdSEUPoq9p5oYEA.png" /><figcaption>output of the command.</figcaption></figure><h3>EXEC into a Docker Container</h3><p>As we have created and started a docker container which is running in the background, let’s enter into.</p><p>List the running container —</p><pre>docker ps <br><br># this will list all the currently running contianers and their metadata</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*--KjREg8FxdtRFbsWriwdA.png" /><figcaption>docker ps</figcaption></figure><p>Copy the continaer ID and run the below command (you do not need to copy full ID, you can always choose any length of ID until it is unique. Since, we have just one container running, if we copy only cc, we can interact with our my-container-1 with this ID only without copying the full continer ID).</p><pre>docker exec -it `continaer-id` /bin/bash</pre><p>At this point, you’d see the the host is changed to root@container-id .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*kvRL7BXqJVck6rnuRCTDVg.png" /><figcaption>docker exec command</figcaption></figure><h3>Create File in the Container</h3><p>Now, go to the /home/ubuntu/ directory and create a directory and a file.</p><pre><br># go to the user&#39;s space <br>cd /home/ubuntu<br><br># create a new directory <br>mkdir my-new-dir<br><br># cd to the new directory <br>cd my-new-dir<br><br># create a new file <br>echo &quot;this is my new file. ok. thanks.&quot; &gt; my-new-file<br><br># see the file properties <br>ls -l </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*X_8YmkX-DqcfkGB3uG5yQg.png" /><figcaption>create new file inside the container</figcaption></figure><h3>Stop the Container</h3><p>We’d now stop the container and exit from it.</p><pre># exit the contianer <br>exit <br><br># see running containers<br>docker ps <br><br># stop the continaer<br>docker stop `container-id` or docker stop `container-name` </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*cGYhjKIhM_mEMrZC9YFBew.png" /><figcaption>stop docker container</figcaption></figure><h3>List All Docker Containers</h3><p>Let’s see all the active and non-active docker containers.</p><pre># command to list all the active/running docker containers <br>docker ps <br><br># command to list all stopped containers <br>docker ps -a </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*fi6i1dK-GBhE39B7gijoIA.png" /><figcaption>listing docker continaers</figcaption></figure><h3>Restart the Container</h3><p>Let’s restart the stopped docker container again.</p><pre><br>#restart a stopped docker container <br>docker start `container-id`<br><br># list the running containers <br>docker ps </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*Vi1xjHHQZUdwKcr6jy71lQ.png" /><figcaption>restart the docker container</figcaption></figure><h3>Verify Data Persistence</h3><p>Let’s verify if the data we’ve written earlier into the docker container is still persistent since we’ve stopped the docker continaer. In order to do so, let’s reattach to the container to verify the data persistence —</p><pre>docker exec -it `container-id` or `container-name` /bin/bash<br><br># from our example using the container-name <br>docker exec -it my-container-1 /bin/bash<br></pre><p>Once we are attached to the container, go to the same directory of my-new-dir and see if my-new-file still exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Uuruyhri4cNKPNuifX5dnQ.png" /><figcaption>data persistence</figcaption></figure><p>You’d see that the data is still there which means data saved in a docker container is persistent even the container was stopped and restarted. This is due to the nature of docker volume. We would learn more about docker volume in our comming blog posts.</p><h3>Delete the Container</h3><p>Let’s delete the container we’ve created —</p><pre># list the running docker container <br>docker ps <br><br># stop the contianer you want to delete <br># NOTE: you must stop any running docker container before you delete them <br>docker stop `container-id` <br><br># delete the container <br>docker rm `container-id`<br><br># verify the container has been deleted <br>docker ps -a </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*AVNikMl-xl3KcgmDqna-vw.png" /></figure><h3>Conclusion</h3><p>In this short introductory post, we have explored the basic life cycle of a docker container. We have get familier with some most used docker command and understood</p><ul><li>docker container run</li><li>create</li><li>restart</li><li>listing running and stopped container</li><li>enter into container and write data inside it</li><li>see the data persistence</li><li>and delete a docker contianer.</li></ul><p>In coming blog, we will explore more advanced workarounds of docker. Happy learning, and keep pushing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07e57f08a6a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>