<?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 Sumeet Shukla on Medium]]></title>
        <description><![CDATA[Stories by Sumeet Shukla on Medium]]></description>
        <link>https://medium.com/@sumeet.k.shukla?source=rss-c810444cfd06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4-dwbdW-keuX0tWHtn2dQg.jpeg</url>
            <title>Stories by Sumeet Shukla on Medium</title>
            <link>https://medium.com/@sumeet.k.shukla?source=rss-c810444cfd06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:45:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumeet.k.shukla/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[Normalization in OLTP vs. OLAP: Striking the Balance]]></title>
            <link>https://medium.com/@sumeet.k.shukla/normalization-in-oltp-vs-olap-striking-the-balance-435b94c53dc2?source=rss-c810444cfd06------2</link>
            <guid isPermaLink="false">https://medium.com/p/435b94c53dc2</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[normalization]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[database-administration]]></category>
            <dc:creator><![CDATA[Sumeet Shukla]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 05:56:19 GMT</pubDate>
            <atom:updated>2023-12-20T05:56:19.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is the lifeblood of modern organizations, driving every aspect of operations and strategic decision-making. But storing and accessing this data efficiently depends greatly on the environment — specifically, whether it’s an Online Transaction Processing (OLTP) system or an Online Analytical Processing (OLAP) system. In this context, the concept of normalization, the process of structuring data to minimize redundancy and optimize storage, takes on different shades of significance.</p><p><strong>OLTP and Normalization: Efficiency Reigns Supreme</strong></p><p>OLTP systems prioritize transactional operations. Think online purchases, bank transactions, or inventory management. They’re constantly bombarded with short, high-volume updates, demanding rapid data retrieval and manipulation. In this environment, normalization takes center stage. By eliminating redundancy and reducing data dependency, normalized structures:</p><ul><li><strong>Minimize storage footprint:</strong> Smaller tables reduce storage costs and improve disk I/O efficiency.</li><li><strong>Enhance data integrity:</strong> Normalized relations maintain consistent data through defined relationships, reducing update anomalies.</li><li><strong>Boost concurrency:</strong> Concurrent access to normalized tables minimizes potential conflicts and maximizes operational speed.</li></ul><p>While high levels of normalization (3rd Normal Form and beyond) achieve these benefits, they can introduce overhead in query execution due to joins between multiple tables. Therefore, finding the sweet spot between sufficient normalization for efficiency and minimizing join complexity for performance is crucial in OLTP systems.</p><p><strong>OLAP and Normalization: Flexibility Matters Most</strong></p><p>OLAP systems focus on data analysis and reporting. They aggregate and analyze historical data from potentially diverse sources, helping identify trends, patterns, and insights for informed decision-making. Here, flexibility and speed of analysis become paramount.</p><p>While some level of normalization remains important for maintaining data integrity and reducing storage needs, OLAP databases often favour denormalization to:</p><ul><li><strong>Pre-aggregate data:</strong> Storing pre-calculated aggregates eliminates the need for complex joins and speeds up analytical queries.</li><li><strong>Reduce join complexity:</strong> Denormalized structures with redundant data minimize joins, facilitating rapid ad-hoc analyses.</li><li><strong>Improve analytical flexibility:</strong> Users can slice and dice data across various dimensions without navigating complex joins.</li></ul><p>However, excessive denormalization can lead to data redundancy, increased storage requirements, and update complexities. The challenge lies in finding the optimal balance between storage efficiency and query performance tailored to the specific analytical needs of the OLAP environment.</p><p><strong>Striking the Balance: Context is Key</strong></p><p>The ideal normalization strategy remains context-dependent:</p><ul><li><strong>Highly transactional OLTP systems:</strong> Focus on high normalization for data integrity and operational efficiency.</li><li><strong>Analytical OLAP systems:</strong> Lean towards denormalization for flexible and rapid analysis, with some level of normalization for efficient storage.</li><li><strong>Hybrid OLTP/OLAP systems:</strong> Implement hybrid normalization strategies to cater to both transactional and analytical needs.</li></ul><p>Ultimately, successful data management relies on understanding the specific requirements of your environment and choosing the normalization approach that best serves your data’s purpose. Embrace this flexibility, and your data will become a powerful tool for driving efficient operations and insightful decision-making.</p><p><strong>Further Exploration:</strong></p><ul><li>Analyze your specific data usage patterns and operational demands.</li><li>Consider available tools and technology that can optimize data retrieval and manipulation.</li><li>Consult with data experts to design a database structure that strikes the perfect balance for your unique needs.</li></ul><p>By tailoring your approach to the unique context of your environment, you can leverage the power of normalization to unlock the full potential of your data, whether in the fast-paced world of OLTP or the insightful realm of OLAP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435b94c53dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Quiet Triumph: Signs You’ve Truly Solved a Database Administration Problem]]></title>
            <link>https://medium.com/@sumeet.k.shukla/the-quiet-triumph-signs-youve-truly-solved-a-database-administration-problem-54a3bf88832d?source=rss-c810444cfd06------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a3bf88832d</guid>
            <category><![CDATA[disaster-response]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[unsung-heroes]]></category>
            <dc:creator><![CDATA[Sumeet Shukla]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 17:07:48 GMT</pubDate>
            <atom:updated>2023-12-16T17:08:41.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvGqEjYwmzrS4X-sFckYeA.png" /></figure><p>Database administrators (DBAs) are the unsung heroes of the digital world. They toil away in the background, ensuring the smooth flow of information that powers our modern lives. But how do they know when they’ve truly solved a database problem?</p><blockquote>It’s not always as clear as a blinking green light or a celebratory “Success!” message.</blockquote><p>Solving a database problem goes beyond mere functionality. It’s about crafting a solution that seamlessly integrates with the bigger picture, enhancing performance, security, reliability, and scalability, all while ensuring business continuity and disaster recovery. So, how do you know you’ve truly crossed the finish line? Here are some subtle but telling signs:</p><p><strong>1. The Performance Whisperer:</strong></p><ul><li>Queries hum along: Gone are the days of users tapping their feet, waiting for sluggish queries. Your optimizations have made transactions zip past, leaving everyone singing the praises of database responsiveness.</li><li>Resource whispers: CPU and memory usage have become the quietest party in the room. Your solution has squeezed the most out of every resource, leaving plenty of room for other applications to breathe.</li></ul><p><strong>2. The Security Sentinel:</strong></p><ul><li>Unauthorized access? Not anymore: Your defenses stand tall, repelling even the most determined intruders. Data breaches are a distant memory, replaced by the comfort of knowing your information is safe and sound.</li><li>Vulnerability whispers: The ghosts of security flaws have been exorcised. Regular scans and proactive patching have kept your database squeaky clean, leaving no room for vulnerabilities to exploit.</li></ul><p><strong>3. The Reliability Rock:</strong></p><ul><li>Downtime? What downtime?: Outages are a thing of the past. Your database is a rock of stability, weathering storms of peak traffic and unexpected events without a flinch.</li><li>Recovery whispers: Even when hiccups occur, they’re mere whispers. Backups are readily available, and recovery procedures are so smooth, users might not even notice.</li></ul><p><strong>4. The Scalability Sorcerer:</strong></p><ul><li>Growth? Bring it on!: Your database stretches and adapts like a seasoned yogi. Increased data volume and user activity are simply opportunities to showcase its flexibility and resilience.</li><li>Cost whispers: Scaling doesn’t have to break the bank. You’ve found the sweet spot between cost and performance, ensuring optimal resource utilization without unnecessary expenditure.</li></ul><p><strong>5. The Business Continuity Whisperer:</strong></p><ul><li>Disaster? We’ve got this: When the unexpected strikes, your plan springs into action like a well-rehearsed orchestra. Data loss is minimized, services are restored quickly, and the business keeps humming along.</li><li>Communication whispers: Stakeholders are kept in the loop, informed and confident in your ability to navigate even the most challenging situations.</li></ul><blockquote>Remember, solving a database problem isn’t about fanfare or accolades. It’s about the quiet satisfaction of knowing you’ve crafted a solution that silently hums in the background, ensuring the smooth operation of the digital world.</blockquote><p>So, the next time you find yourself staring at a blinking green light or a “Success!” message, take a moment to appreciate the symphony of smaller victories that led you there. You, the quiet hero, have truly solved a database problem.</p><p>Share your success stories with your fellow DBAs! Documenting your challenges and solutions can not only provide valuable insights for others but also serve as a reminder of your own expertise and the impact you have on the world behind the scenes.</p><p><em>Now go forth and conquer, fellow database warriors! Remember, the true signs of victory are often the whispers, not the shouts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a3bf88832d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Architecture]]></title>
            <link>https://medium.com/@sumeet.k.shukla/postgresql-architecture-6df259dc1145?source=rss-c810444cfd06------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df259dc1145</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql-architecture]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgresql-internal]]></category>
            <category><![CDATA[shared-buffers]]></category>
            <dc:creator><![CDATA[Sumeet Shukla]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 12:15:58 GMT</pubDate>
            <atom:updated>2023-01-12T14:07:43.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5h1WscY02chzU_3lavW1aA.png" /><figcaption>PostgreSQL Architecture</figcaption></figure><p>PostgreSQL instance consists of set of Process and Memory. PostgreSQL uses a simple “process per-user” client/server model. The major processes are:</p><ol><li>The ‘postmaster’ which is:</li></ol><ul><li>supervisory daemon process,</li><li>‘postmaster’ is attached to shmmem segment but refrains from accessing to it.</li><li>always running waiting for connection requests</li></ul><blockquote>2. Utility processes ( bgwriter, walwriter, syslogger, archiver, statscollector, <em>checkpointer</em> and autovacuum launcher ) and</blockquote><p>3. User Backend process ( postgres process itself, Server Process )</p><p>When a client request for connection to the database, firstly request is hit to Postmaster daemon process. After performing authentication and authorization it forks one new backend server process (postgres). Henceforth, the frontend process and the backend server communicate directly without intervention by the postmaster. The postmaster is always running, waiting for connection requests, whereas frontend and backend processes come and go. The libpq library allows a single frontend to make multiple connections to backend processes.</p><p>However, each backend process is a single-threaded process that can only execute one query at a time; so the communication over any one frontend-to-backend connection is single-threaded.<br>Postmaster and postgres servers run with the user ID of the PostgreSQL “superuser”.</p><p>One postgres<em> </em>process exists for every open database session. Once authenticated with user connection, it directly connects (with who and for what purpose) with shared memory.</p><h3>POSTGRESQL SHARED MEMORY</h3><p><strong>Shared Buffers:</strong></p><p>Sets the amount of memory the database server uses for shared memory buffers. The default is typically 32MB. Larger settings for <em>shared_buffers</em> usually require a corresponding increase in <em>checkpoint_segments</em>, in order to spread out the process of writing large quantities of new or changed data over a longer period of time. Below 3 parameters should be discussed:</p><ul><li>bgwriter_delay</li><li>bgwriter_lru_maxpages</li><li>bgwriter_lru_multiplier</li></ul><p><strong>WAL Buffers</strong></p><p>The amount of shared memory used for WAL data that has not yet been written to disk. The default setting of -1 selects a size equal to 1/32nd (about 3%) of <em>shared_buffers</em>, but not less than 64kB nor more than the size of one WAL segment, typically 16MB. This value can be set manually if the automatic choice is too large or too small, but any positive value less than 32kB will be treated as 32kB. This parameter can only be set at server start. The contents of the WAL buffers are written out to disk at every transaction commit, so extremely large values are unlikely to provide a significant benefit. However, setting this value to at least a few megabytes can improve write performance on a busy server where many clients are committing at once. The auto-tuning selected by the default setting of -1 should give reasonable results in most cases.</p><p><strong>CLOG Buffers:</strong></p><p><em>$PGDATA/pg_clog</em> contains a log of transaction metadata. This log tells PostgreSQL which transactions completed and which did not. The clog is small and never has any reason to become bloated, so you should never have any reason to touch it.</p><h3>POSTGRESQL PER BACKEND MEMORY</h3><p><strong>work_mem</strong></p><p>Specifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files. Default is 1M. Note that for a complex query, several sort or hash operations might be running in parallel; each operation will be allowed to use as much memory as this value specifies before it starts to write data into temporary files. Also, several running sessions could be doing such operations concurrently. Therefore, the total memory used could be many times the value of <em>work_mem</em>; it is necessary to keep this fact in mind when choosing the value.</p><p><strong>temp_buffers</strong></p><p>Sets the maximum number of temporary buffers used by each database session. Default is 8M. The setting can be changed within individual sessions, but only before the first use of temporary tables within the session; subsequent attempts to change the value will have no effect on that session.</p><p><strong>maintenance_work_mem</strong></p><p>Specifies the maximum amount of memory to be used by maintenance operations, such as VACUUM, CREATE INDEX, and ALTER TABLE ADD FOREIGN KEY. Default is 16M. Since only one of these operations can be executed at a time by a database session, and an installation normally doesn’t have many of them running concurrently, it’s safe to set this value significantly larger than work_mem.</p><h3>UTILITY PROCESSES:</h3><p>Mandatory processes: We cannot Enable/Disable these processes.</p><ul><li>BGWriter</li><li>WAL Writer</li><li>Checkpointer</li></ul><p>Optional Processes:</p><ul><li>Stats-collector</li><li>Autovacuum launcher</li><li>Archiver</li><li>Syslogger</li><li>WAL Sender</li><li>WAL Receiver</li></ul><p><strong>BGWriter</strong></p><p>The function of background writer is to issue writes of “dirty” (new or modified) shared buffers. It writes shared buffers so that server processes handling user queries seldom or never need to wait for a write to occur. However, the background writer does cause a net overall increase in I/O load, because while a repeatedly-dirtied page might otherwise be written only once per checkpoint interval, the background writer might write it several times as it is dirtied in the same interval. Below parameters can be used to tune the behavior for local needs.</p><p>bgwriter_delay: Specifies the delay between activity rounds for the background writer. Default is 200ms.</p><p>bgwriter_lru_maxpages: In each round, no more than this many buffers will be written by the background writer. Setting this to zero disables background writing (except for checkpoint activity). The default value is 100 buffers.</p><p>bgwriter_lru_multiplier: The number of dirty buffers written in each round is based on the number of new buffers that have been needed by server processes during recent rounds. The default is 2.0.</p><p>Smaller values of bgwriter_lru_maxpages and bgwriter_lru_multiplier reduce the extra I/O load caused by the background writer, but make it more likely that server processes will have to issue writes for themselves, delaying interactive queries.</p><p><a href="https://www.postgresql.org/docs/15/kernel-resources.html">https://www.postgresql.org/docs/15/kernel-resources.html</a></p><p><strong>WAL Writer</strong></p><p>WAL writer process writes and fsync WAL at convenient Intervals. WAL buffers holds the changes made to the database in the transaction logs, in order to guarantee transaction security. WAL buffers are written out to the disk at every transaction commit, as WAL writer process is responsible to write on to the disk. WAL_WRITER_DELAY parameter for invoking the WAL Writer Process, however there are other parameters which also keeps the WAL Writer busy.</p><p><strong>Stats Collector</strong></p><p>Stats collector process will collect the information about the server activity. It count number of access to the tables and indexes in both disk-block and individual row items. It also tracks the total number of rows in each table, and information about VACUUM and ANALYZE actions for each table. Collection of statistics adds some overhead to query execution, whether to collect or not collect information. Some of the parameter in the postgresql.conf file will control the collection activity of the stats collector process. <a href="https://www.postgresql.org/docs/15/monitoring-stats.html">Click here to know more about the stats collector process and its related parameters</a>.</p><p><strong>Autovacuum Launcher</strong></p><p>For automating the execution of VACUUM and ANALYZE command, Autovacuum Launcher is a daemon process consists of multiple processes called autovacuum workers. Auto-vacuum launcher is a charge of starting autovacuum worker processes for all databases. Launcher will distribute the work across time, attempting to start one worker on each database for every interval, set by the parameter autovacuum_naptime. One worker will be launched for each database, set by the parameter autovacuum_max_workers. Each worker process will check each table within its database and execute VACUUM or ANALYZE as needed. Following will brief about the AUTOVACUUM LAUNCHER PROCESS parameters.</p><p><a href="https://www.postgresql.org/docs/15/runtime-config-autovacuum.html">Click here to know more about AUTOVACUUM LAUNCHER PROCESS parameters</a></p><p><strong>Syslogger Process / Logger Process:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBcMCPvkVWOgIjfGEXi7_g.png" /><figcaption>Syslogger Process</figcaption></figure><p>As per the figure, it is clearly understood that all the utility process + User backends + Postmaster Daemon are attached to the <em>syslogger</em> process for logging the information about their activities. Every process information is logged under $PGDATA/pg_log with the file .log.</p><p>Debugging more on the process information will cause overhead on the Server. Minimal tuning is always recommended, however, increasing the debug level when required. Below link will brief further on logging parameters.</p><p><a href="https://www.postgresql.org/docs/15/runtime-config-logging.html">https://www.postgresql.org/docs/15/runtime-config-logging.html</a></p><p><strong>Archiver</strong></p><p>Archiver process is optional process, default is OFF.</p><p>Setting up the database in Archive mode means to capture the WAL data of each segment file once it is filled and save that data somewhere before the segment file is recycled for reuse.</p><ol><li>On Database Archivelog mode, once the WAL data is filled in the WAL Segment, that filled segment named file is created under PGDATA/pg_xlog/archive_status by the WAL Writer naming the file as “.ready”. File naming will be “segment-filename.ready”.</li><li>Archiver Process triggers on finding the files which are in “.ready” state created by the WAL Writer process. Archiver process picks the ‘segment-file_number’ of .ready file and copies the file from $PGDATA/pg_xlog location to its concerned Archive destination given in ‘archive_command’ parameter(postgresql.conf).</li><li>On successful completion of copy from source to destination, archiver process renames the “segment-filename.ready” to “segment-filename.done”. This completes the archiving process.</li></ol><p>It is understood that, if any files named “segement-filename.ready” found in $PGDATA/pg_xlog/archive_status. They are the pending files still to be copied to Archive destination.</p><p>For more information on parameters and Archiving, <a href="https://www.postgresql.org/docs/15/continuous-archiving.html">https://www.postgresql.org/docs/15/continuous-archiving.html</a></p><p>Comments/suggestion would be greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df259dc1145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install and Configure pgBadger for PostgreSQL on Linux]]></title>
            <link>https://medium.com/@sumeet.k.shukla/install-and-configure-pgbadger-for-postgresql-on-centos-2dfd01346896?source=rss-c810444cfd06------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dfd01346896</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[reporting-in-postgres]]></category>
            <category><![CDATA[log-analyzer]]></category>
            <category><![CDATA[pgbadger]]></category>
            <dc:creator><![CDATA[Sumeet Shukla]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 05:53:12 GMT</pubDate>
            <atom:updated>2023-01-12T13:54:05.736Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes, one of the most important things is knowing how the databases are used. Indeed if we know what are the slowest queries, the most frequent queries, etc.; we can optimize the databases (by adding an index, changing a query or modifying a schema/structure) and thus improve the performance! To do this, you have to analyse PostgreSQL activity logs. Analysing can be extremely complicated, so you have to use a log analyser to process your data. pgBadger will help you to create reports, and monitor your database activity. So here is how you can Install and Configure pgBadger for PostgreSQL on CentOS 7.</p><pre>#Download the latest source:<br>cd /var/lib/pgsql/9.6<br>wget https://github.com/dalibo/pgbadger/archive/v7.1.tar.gz<br><br>#Extract and change directory:<br>tar -xvf v7.1.tar.gz<br>cd pgbadger-7.1/<br><br>#Install PERL MakeMaker if not already installed:<br>yum -y install perl-ExtUtils-MakeMaker<br><br>#Compile and install:<br>perl Makefile.PL<br>yum -y install make<br>make &amp;&amp; sudo make install<br><br>#Switch user to postgres and edit the configuration file:<br>su - postgres<br>vi /var/lib/pgsql/data/postgres.conf<br><br>#turn on logging for pgbadger by editing the line after # What to Log<br>log_min_duration_statement = 0<br>log_line_prefix = &#39;%t [%p]: [%l-1] user=%u,db=%d &#39;<br>log_checkpoints = on<br>log_connections = on<br>log_disconnections = on<br>log_lock_waits = on<br>log_temp_files = 0<br><br>#postgreSQL requires a restart to pickup the logging changes:<br>service postgresql restart</pre><p><strong>Command to generate report from a specific logfile</strong></p><pre>ln -s /var/lib/pgsql/9.6/pgbadger-7.1/pgbadger /usr/bin/pgbadger<br>pgbadger -f stderr -s 10 -T PGBadger-localhost.localdomain-20151202 -q -o /var/www/html/pgbadger/report`date +\%Y-\%m-\%d`.html /var/lib/pgsql/9.4/data/pg_log/postgresql-2015-12-28.log</pre><p>You can use a <em>cron</em> job to automatically generate pgbadger reports if logs have been created. Here is my /etc/cron.daily/pgbadger-daily_process:</p><pre>#!/bin/bash<br>#script to automatically generate pgbadger report according to the yesterday&#39;s PostgreSQL log<br>PGBADGER_SCRIPT=&#39;/var/lib/pgsql/9.6/pgbadger-7.1/pgbadger&#39;<br>PGBADGER_OPTIONS=&quot;-f stderr -s 10 -T PGBadger-`hostname`-`date --date=&#39;yesterday&#39; +%Y%m%d` -q&quot;<br>PGLOG_PATH=&#39;/var/lib/pgsql/9.6/data/pg_log&#39;<br>PGLOG_FILE_NAME=&quot;postgresql-`date --date=&quot;yesterday&quot; +%Y-%m-%d`.log&quot;<br>PGBADGER_RESULT_FILE=&quot;/var/www/html/pgbadger-reports.epps-erp.com/pgbadger-`hostname`-`date --date=&quot;yesterday&quot; +%Y-%m-%d`&quot;.html<br>PGBADGER_FULL_COMMAND=&quot;$PGBADGER_SCRIPT $PGBADGER_OPTIONS -o $PGBADGER_RESULT_FILE $PGLOG_PATH/$PGLOG_FILE_NAME&quot;<br><br>#################################################################<br>echo &quot;$0 - `date` - INFO - job starts&quot;<br>if [ -e &quot;$PGLOG_PATH/$PGLOG_FILE_NAME&quot; ]<br>then<br>    echo &quot;$0 - `date` - INFO - launching the creation of pgbadger report with $PGLOG_PATH/$PGLOG_FILE_NAME...&quot;<br>    $PGBADGER_FULL_COMMAND<br>    if [ $? -eq 0 ]<br>    then<br>        echo &quot;$0 - `date` - OK - success to create pgbadger report&quot;<br>    else<br>        echo &quot;$0 - `date` - ERROR - problem during the execution of: $PGBADGER_FULL_COMMAND&quot;<br>        exit 1<br>    fi<br>else<br>    echo &quot;$0 - `date` - INFO - log $PGLOG_PATH/$PGLOG_FILE_NAME not found&quot;<br>fi<br>echo &quot;$0 - `date` - INFO - job done&quot;</pre><p>This cron job will automatically create pgbadger reports according to yesterday’s PostgreSQL log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgpmsYTzduRLlT3z4NpG6g.png" /></figure><p>That’s all! Thanks to pgBadger that tells you everything about your database activity 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dfd01346896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving AWS Aurora RDS load balancing problem with pgPool-II]]></title>
            <link>https://medium.com/talabat-tech/solving-aws-aurora-rds-load-balancing-problem-with-pgpool-ii-d54897c95176?source=rss-c810444cfd06------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54897c95176</guid>
            <category><![CDATA[pgpool-ii]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[aurora]]></category>
            <dc:creator><![CDATA[Sumeet Shukla]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 13:04:53 GMT</pubDate>
            <atom:updated>2020-10-08T09:15:58.880Z</atom:updated>
            <content:encoded><![CDATA[<p>DNS-based load balancing has been around for a long time. AWS Aurora relies on this technology for load balancing the read replicas behind the reader endpoint. Recently, here at talabat, we have observed some incidents due to sudden spikes in traffic and the load not getting properly balanced across all the reader nodes, which would cause some nodes to be over-utilized and some others to be underutilized as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGEOOlznPnMdI76obupYNQ.png" /></figure><p>So, we took a deep dive into how the writer and reader endpoints load balancing works. AWS uses DNS round robin to route traffic to the reader endpoints with a TTL of five seconds. This is when we realized that the underlying algorithm may be suitable for a consistent traffic pattern but not efficient for traffic spikes which is very common pattern with our traffic pattern because the split-second traffic peaks could result in inconsistent load distribution across the reader nodes.</p><p>We decided to do little experiment by querying the reader endpoint of one of our Aurora clusters which has three replicas and below are the results:</p><h3>First Test</h3><pre><strong>for</strong> ((i=0;i&lt;100;i++)); <strong>do</strong> dig CNAME rds.cluster-ro-abcdefghij.eu-west-1.rds.amazonaws.com +short &gt;&gt; output.txt; <strong>done</strong>; cat output.txt | sort | uniq -c ; rm output.txt;</pre><pre>47 rds-1.abcdefghij.eu-west-1.rds.amazonaws.com.<br>53 rds-4.abcdefghij.eu-west-1.rds.amazonaws.com.</pre><h3>Second Test</h3><pre><strong>for</strong> ((i=0;i&lt;100;i++)); <strong>do</strong> dig CNAME rds.cluster-ro-abcdefghij.eu-west-1.rds.amazonaws.com +short &gt;&gt; output.txt; <strong>done</strong>; cat output.txt | sort | uniq -c ; rm output.txt;</pre><pre>47 rds-1.abcdefghij.eu-west-1.rds.amazonaws.com.<br>53 rds-4.abcdefghij.eu-west-1.rds.amazonaws.com.</pre><h3>Third Test</h3><pre><strong>for</strong> ((i=0;i&lt;100;i++)); <strong>do</strong> dig CNAME rds.cluster-ro-abcdefghij.eu-west-1.rds.amazonaws.com +short &gt;&gt; output.txt; <strong>done</strong>; cat output.txt | sort | uniq -c ; rm output.txt;  </pre><pre>28 rds-3.abcdefghij.eu-west-1.rds.amazonaws.com. <br>72 rds-4.abcdefghij.eu-west-1.rds.amazonaws.com.</pre><p>In these three tests, the maximum number of endpoints returned by the DNS server was two instead of three. Also, the last test validated our claim of the inconsistency in the load balancing of the reader endpoints.</p><p>The option of using the recently announced RDS Proxy service which could have been the life-saver for us wasn’t suitable for our use-case because RDS Proxy only connects to the writer endpoints and doesn’t support connection pooling for reader endpoints.</p><blockquote>“In an Aurora cluster, all of the connections in the connection pool are handled by the Aurora writer instance. To perform load balancing for read-intensive workloads, you still use the reader endpoint directly for the Aurora cluster.”<br>Reference: <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy.html">https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy.html</a></blockquote><p>Now, in order to avoid the spikes and to utilize the newly autoscaled reader nodes, we had to find a solution to evenly distribute the load across all the RDS nodes.</p><p>We had known that pgPool-II (a reverse proxy server sitting between clients and PostgreSQL) is a very promising tool and also takes care of connection pooling apart from load balancing but it has below shortcomings:</p><ul><li>It only supports static configuration of backends which doesn’t work for aurora with autoscaling enabled.</li><li>It only supports auto-healing for PostgreSQL backends if replication status enabled (this is disabled in aurora).</li><li>It also does not natively supports container/cloud environment. Our applications run on Kubernetes and we wanted to use kubernetes for pgPool-II deployment as well.</li></ul><p>So we thought to write a <a href="https://golang.org/">goLang</a> wrapper on top of stock pgPool-II to address the shortcomings described above to leverage load balancing and connection pooling capabilities of pgPool-II. Special thanks to <a href="https://medium.com/u/7ed0bcfc6c21">Oluwaseun Obajobi (Oba)</a> for writing and implementing the goLang wrapper.</p><p>With our mind set on building this application to be cloud-native, the application was packaged as a docker image and deployed in our Kubernetes cluster with helm chart. Running containers in Kubernetes production especially a middleware between a service and database has to be built with extreme reliability and consider scenarios like:</p><ul><li>Accepting traffic only when the container is healthy.</li><li>Draining database connections before shutdown.</li></ul><h3>Accepting traffic only when the container is healthy</h3><p>Pgpool-II doesn’t expose any endpoint for health-check but we can actually verify the availability by running a simple PSQL command</p><pre>PGCONNECT_TIMEOUT=15 PGPASSWORD=pass psql -U postgres -d postgres -h 127.0.0.1 -tA -c &quot;SELECT 1&quot;</pre><p>The above command was wrapped into a simple command which was used as Kubernetes readinessProbe as below:</p><pre>deployment.yaml <br>--- <br><strong>readinessProbe</strong>:   <br>  <strong>exec</strong>:     <br>    <strong>command</strong>: [&quot;rds-pgpool&quot;, &quot;check&quot;]</pre><p>With the above, we can guarantee that traffic are only accepted when Pgpool is actually up and ready to serve traffic.</p><h3>Draining database connections before shutdown</h3><p>pgPool-II has two shutdown modes which are smart or fast. According to <a href="https://www.pgpool.net/docs/latest/en/html/pgpool.html">this documentation</a>, if smart option is specified, pgPool-II will wait until all clients are disconnected before shutting down.</p><p>pgpool -m smart stop</p><p>This definitely was the perfect option for us to safely shutdown the containers without impacting the application clients. To safely implement the graceful shutdown in Kubernetes, we used preStop hook as described below:</p><pre>deployment.yaml <br>--- <br><strong>lifecycle</strong>:   <br>  <strong>preStop</strong>:     <br>    <strong>exec</strong>:       <br>      <strong>command</strong>: [&quot;rds-pgpool&quot;, &quot;stop&quot;]</pre><p>The outcome of implementation resulted into an evenly balanced database traffic across our endpoint with some of the positive outcomes as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yloPvYjB7DKtwmcPRqwgLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K46WLL8oH5MgQuPtKS9kaA.png" /></figure><p>We did a load test with the pgPool-II implementation using Helm charts on Kubernetes and we could clearly see the difference in how smoothly the CPU utilization scaled up. The load is almost equally balanced across all the nodes including the newly autoscaled ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou_yZWySfEWC-MpWNFv-9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pt1PdsRbTFb45UJ6U4y31g.png" /></figure><p>After autoscaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzthjlM2Xxe_n1UFjMkc7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCw9OiwpOhOvY5EWNQ7hAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9kTsW53eCnIMZ1K3ReA_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_JnNd-aA7Sc-2S8B0dklA.png" /></figure><p>The same thing goes with the number of connections or sessions as well.</p><p>With this implementation, at talabat, we’ve been able to evenly distribute database connections between our replica endpoints with close to 100% efficiency. We are still actively looking at the possibility of improving the read replica scaling which takes about eight minutes.</p><p>Subscribe to this blog and don’t miss our next article about how we solved the slow autoscaling with predictive scaling!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54897c95176" width="1" height="1" alt=""><hr><p><a href="https://medium.com/talabat-tech/solving-aws-aurora-rds-load-balancing-problem-with-pgpool-ii-d54897c95176">Solving AWS Aurora RDS load balancing problem with pgPool-II</a> was originally published in <a href="https://medium.com/talabat-tech">talabat Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>