<?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 Divyanshu on Medium]]></title>
        <description><![CDATA[Stories by Divyanshu on Medium]]></description>
        <link>https://medium.com/@shekdivyanshu?source=rss-1bef6b1b95c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*07a8AgVtrZfBUCOO</url>
            <title>Stories by Divyanshu on Medium</title>
            <link>https://medium.com/@shekdivyanshu?source=rss-1bef6b1b95c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:09:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shekdivyanshu/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[But What is Storage : HDDs, SSDs, EBS and more]]></title>
            <link>https://medium.com/@shekdivyanshu/but-what-is-storage-hdds-ssds-ebs-and-more-0bd9a94e192c?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd9a94e192c</guid>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 18:38:23 GMT</pubDate>
            <atom:updated>2026-09-16T04:03:41.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the start of another multipart blog, this time it’s all about storage and a bit of AWS.</p><p>Let’s start from the building blocks : the machines powering storage : HDD and SSDs.</p><h3>HDDs (Hard Disk Drives)</h3><p>A HDD is a mechanical device that holds bits in a circular ring (yes, your data is just binary). There is a rotating circular disk having your data, and a rod like structure pivoted one one end is responsible for reading the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6MqKtkcZ29_toNLca1KIg.png" /><figcaption>The blackened area is the target spot for reading data. The arm will move in such a way as it lands exactly there.</figcaption></figure><p>The head (rod structure) will rotate such that the tip lands exactly where the data needs to be read from/written to.</p><p>And this is pretty cheap and simple. That’s the reason they dominated the storage market for so long.</p><p>The problem started when the size of data humans started creating and reading exploded dramatically. As you can see, if you need to read any piece of information you need to wait for the disc to rotate fully before the head can align itself. Couple that with random reads and writes, every operation would need to wait for a rotation.</p><p>HDDs are still in use today, mainly because they are cheap. And they are still good for sequential IOPS and low traffic databases.</p><h3>SSDs (Solid State Drives)</h3><p>SSDs are made up of a controller block ( something that remembers where data is present, manages reads and writes) and a few other blocks (called dies) where the actual data is stored. These dies are actually NAND chips that retain data by holding charges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*haL19C4RUOF2JbBU.jpg" /><figcaption>src: <a href="https://fossbytes.com/what-is-ssd-how-ssds-work-features/">https://fossbytes.com/what-is-ssd-how-ssds-work-features/</a></figcaption></figure><p>They are massively parallel, can support random IOPS, don’t have any mechanical waiting time and are faster.</p><p>This is what modern hardwares, requiring high IOPS with random reads and writes, use.</p><p>If you want to understand it in more detail, I found this video very much helpful: <a href="https://youtu.be/JwYttFnXRps">https://youtu.be/JwYttFnXRps</a></p><p>However they are much more costlier than HDDs. They also lose their charge gradually over a few years, and need to be replaced before we lose data.</p><h4>NVMe <strong>(Non-Volatile Memory Express)</strong></h4><p>A protocol that makes the SSDs even more powerful. It allows for far greater queue lengths and allows maximum usage of multiple lanes in the PCIe (the electronic path along which data can flow) for maximum throughput.</p><p>Most modern SSDs are by default following the NVMe protocol. SATA is another protocol, that is a bit old now, but still in wide use.</p><h3>Types of Storage Interfaces</h3><p>Whatever the underlying hardware is, we ultimately write data in blocks/pages/chunks. Different names but the idea is same, break the data into fix sized chunks and store them.</p><p>However, we love abstractions and so we have come up with various forms of data storage interfaces:</p><ol><li>Block storage</li><li>File storage</li><li>Object Storage</li></ol><h3>Block Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*2Z_lA5SdAIgWnu0bU11x4A.png" /></figure><p>The lowest level interface you can get to the disk is block storage. A block storage lets you read or write data in chunks of (usually) 4kB or 8kB. It is built directly on top of the underlying hardware.</p><p>Everything is byte addressable, if you need a write, go to byte location ‘X’. It is as fast as the hardware lets you (HDD or SSD).</p><h4>AWS EBS</h4><p>In the world of cloud storage (we will focus on AWS only), this is available to users through the AWS EBS service, which stands for <em>Elastic Block Storage</em>. EBS is a service that you can connect to other services such as an EC2 instance.</p><p>Usually services like EC2 have ephemeral storage. It means if the server dies, all your data is lost as well. Even the ‘i’ family of instances, that are called “storage optimised” use a NVMe SSD, which lives on the server itself. IO is extremely fast, but if the entire server goes down, data is irrecoverable.</p><p>If you are using a by-default distributed data system such as Cassandra, ElasticSearch or DFS, a single server dying isn’t a big problem. This is because these systems work on replication and quorums. Any write is successful only if it goes to <em>N</em> number of other EC2 instances. We can always spin up another EC2, and take backup from the data stored on other machines.</p><p>The problem lies with monolithic or systems following a leader based replication. Postgres and MySQL servers (which half of the world uses) are prime examples. There is a single leader, and if it dies without any warning, there is no way to recover recent data.</p><p>Now, if you are a team of several talented engineers you can create fault-tolerant backup workflows with S3 and WAL archives (read this blog for massive postgres backups). However, for most other oragnisations EBS is the way to go. It is relatively costly as compared to a custom backup system, but is the easier and a stress-free solution.</p><p>Just connect your EC2 with an EBS service, and you can be assured that you never lose data. It is however important to understand that EBS servers can die too, but they are replicated automatically across zones. It is something done automatically by AWS and we do not need to think about it.</p><p><em>Note</em>: You can <strong><em>not</em></strong> connect storage optimised family of EC2 servers with an EBS.</p><p>But we said block storages are as fast as the hardware lets us. So how do we actually select the hardware? EBS lets you choose between following types of instances:</p><ul><li>gp2, gp3 —General purpose. Based on solid state drives.</li><li>io1, io2 — IOPS optimised. Based on solid state drives.</li><li>st1 — Throughput optimised. Based on hard disk drives.</li><li>sc1 — Cold, cheap throughput. Based on hard disk drives.</li></ul><p>The numbers just indicate the generation (higher is better). The general purpose family is optimised for medium level traffic (or boot volumes) and can scale from 3,000 IOPS to 16,000 IOPS. While the IO optimised ‘io’ family can scale upto 64,000 IOPS and is made for extreme performance.</p><p>The ‘st1’ and ‘sc1’ family are relatively slower and better for sequential IO and throughput. Example applications include log processing, big data/EMR, streaming writes. They are also cheaper than their SSD counterparts.</p><p>That being said, it is important to understand, no matter how fast the operations are, the latency for the end user is still capped by network speed. The time it takes data to travel from EC2 to an EBS volume can be matter of concern for many applications.</p><p>Here is a tweet by one of my favourite teachers Ben Dickens :</p><p><a href="https://x.com/BenjDicken/status/2092975429091233848?s=20">https://x.com/BenjDicken/status/2092975429091233848</a></p><p>You can see just how massive the difference between a local NVMe SSD and an EBS is. And if it matters for you, maybe you will go back to making a fault tolerant backup system, that can handle a local NVMe storage dying, without any data loss.</p><h3>File System Storages</h3><p>We all are familiar with this one. File, files inside folders, sub-folders in folders (nested directories). It is just an abstraction over block storage. Every programming tutorial for beginners cover this. But let’s go back and check it out once more:</p><pre>from fs import open_fs<br><br>def demonstrate_file_system_abstraction():<br>    with open_fs(&#39;osfs://&#39;) as home_fs:<br>            <br>        # 1. Writing text files using unified methods<br>        file_path = &#39;blog_demo/sub_folder/article.md&#39;<br>        home_fs.settext(file_path, &quot;# File System Storages&quot;)<br>        print(f&quot;Wrote content to: {file_path}&quot;)<br>        <br>        # 2. Reading the text back<br>        content = home_fs.gettext(file_path)<br>        print(content)</pre><p>That is it !</p><p>Now take it to a distributed global level, that’s what AWS EFS (Elastic File Storage) is. It uses something called as NFS (Networked File System) which is a protocol for distributed file storages. Essentially, it makes it possible for multiple EC2 servers to share the same file. It is not possible with EBS, as one EBS can be attached to only one other EC2 instance at a time.</p><p>EFS auto-scales according to your workload, offering a pay-as-you-go service. It abstracts all the complexities and makes you feel as if you were working with a local directory itself. And the best part is, EFS can work with lambdas, EC2 or containers concurrently at low latencies.</p><p>EFS is good whenever multiple machines need to see the exact same files, at the same time, and some machines die, others spin up — which is common in web fleets, distributed ML jobs, analytics workers, and ephemeral CI runners alike. Object storage (S3) doesn’t give you real file semantics (locking, directories, POSIX permissions), and EBS only attaches to one instance — EFS is the option built specifically for this “many machines, one shared filesystem” shape.</p><p>In theory, EFS is the costliest storage due to coordination and concurrency features. However, EBS can cost more if not managed well. This is because EBS costs you for the amount of storage you provision (you might have acquired a 500GB volume but be using only 25GB), whereas with S3 and EFS you only need to pay for what you store.</p><h3>More To Read/Watch:</h3><ol><li>EFS: <a href="https://medium.com/@anjalimore689/understanding-aws-efs-the-simplest-way-to-share-files-across-aws-6c0be6ed5efe">https://medium.com/@anjalimore689/understanding-aws-efs-the-simplest-way-to-share-files-across-aws-6c0be6ed5efe</a></li><li>EFS: <a href="https://sedai.io/blog/aws-efs-elastic-file-system">https://sedai.io/blog/aws-efs-elastic-file-system</a></li><li>EBS: <a href="https://sedai.io/blog/ebs-aws-elastic-block-store-basics">https://sedai.io/blog/ebs-aws-elastic-block-store-basics</a></li><li>Storage Devices: <a href="https://www.youtube.com/live/vhRqUrGjK2g?si=z2uriUL5rZoz15b5">https://www.youtube.com/live/vhRqUrGjK2g</a></li></ol><p>That’s it for this part. We will meet in the next part with deep dive on S3. Till then byeee :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd9a94e192c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything About Your Postgres Server Monitoring — part II]]></title>
            <link>https://medium.com/@shekdivyanshu/everything-about-your-postgres-server-monitoring-part-ii-22367f559dd7?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/22367f559dd7</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 02:49:41 GMT</pubDate>
            <atom:updated>2026-08-23T02:49:41.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*DyX4ycvyiCYMccxHGOecag.png" /></figure><p>If you haven’t checked out the first part of this blog please give it a go: <a href="https://medium.com/@shekdivyanshu/everything-about-your-postgres-server-monitoring-part-i-b3d0a974981c"><strong><em>Part-I</em></strong></a>. In the last part we covered basic understanding of statistics, dynamic stats, followed by important numbers related to WAL, checkpoints and archiving.</p><p>In this blog post we shall continue from the 4th part :</p><h3>Part Four — Database, Table &amp; Index Statistics</h3><p>Now that we understand the transaction and WAL machinery, we can move to the part that is much more directly connected to diagnosing slow tables, missing indexes, and vacuum problems.</p><p>This is where we start asking questions like:</p><p><em>Is this table being scanned too much?</em></p><p><em>Is autovacuum keeping up?</em></p><p><em>Are my indexes actually being used?</em></p><p><em>Is my cache doing its job?</em></p><h3>pg_stat_database</h3><p>pg_stat_database gives us one row per database and acts almost like a database-wide health dashboard.</p><p>It includes the current number of connections, committed and rolled-back transactions, cache hits and reads, temporary files, deadlocks, I/O timing, and the time at which the statistics were reset.</p><p>numbackends tells you the current number of connections.</p><p>xact_commit and xact_rollback tell you how many transactions have committed and rolled back.</p><p>blks_read and blks_hit are the values used to calculate cache hit ratio.</p><p>temp_files and temp_bytes tell you about temporary files created on disk, which can indicate that queries needed more work_mem than was available and spilled work to disk.</p><p>deadlocks counts detected deadlocks.</p><p>And blk_read_time and blk_write_time measure cumulative time spent waiting on those reads and writes. These require track_io_timing to be enabled, and they are duration counters rather than timestamps.</p><p>Finally, stats_reset tells you when the counters were last reset, which is important because you should use that timestamp when calculating rates.</p><h3>What Should We Actually Check?</h3><p>The first obvious metric is the cache hit ratio:</p><pre>blks_hit / (blks_hit + blks_read)</pre><p>For a typical OLTP workload, around 99% or higher is a common rule of thumb. A low ratio can mean that shared_buffers is too small or that the workload simply contains a lot of cold reads.</p><p>Then look at rollbacks. If the rollback ratio is unusually high compared to commits, it may indicate application-level errors or retry behaviour.</p><p>Temporary files are another very useful signal. If temp_files or temp_bytes keeps climbing, queries are spilling work to disk because they don&#39;t have enough work_mem for what they are trying to do.</p><p>Deadlocks should ideally be zero or very rare. If they are occurring consistently, there is usually an application-level locking-order problem worth investigating.</p><p>And if you’re using a connection pooler, numbackends is especially useful because it tells you how many real database connections are currently open compared with your available connection capacity.</p><h3>Is blks_hit The Same As hits In pg_stat_io?</h3><p>They represent the same general idea, but the scope is different.</p><p>blks_hit in pg_stat_database represents total cache hits for the whole database across all backends.</p><p>pg_stat_io gives you a more detailed breakdown of hits by backend type, object, and context.</p><p>So one is your broad database-level view, while the other lets you ask exactly <strong>who</strong> is getting those hits and <strong>what kind of I/O</strong> they are doing.</p><h3>pg_stat_database_conflicts</h3><p>If you are running a standby, pg_stat_database_conflicts becomes useful.</p><p>This view tells you why queries on the standby were cancelled because of conflicts with replication.</p><p>For example, confl_tablespace means the standby needed a tablespace that was dropped on the primary.</p><p>confl_lock means a standby query held a lock that the replayed WAL change needed.</p><p>confl_snapshot means a query needed an old snapshot, but the corresponding data had already been vacuumed away on the primary.</p><p>confl_bufferpin means a standby query pinned a buffer that WAL replay needed.</p><p>And confl_deadlock means replay caused a deadlock.</p><p>Ideally, these should all stay at zero or close to zero. If they keep increasing, standby queries are being cancelled to allow replication to continue. Depending on the situation, hot_standby_feedback = on or increasing max_standby_streaming_delay can help.</p><h3>pg_stat_all_tables</h3><p>Now let’s go one level deeper and look at individual tables.</p><p>pg_stat_all_tables gives you one row per table in the current database. There are three versions of this view: pg_stat_all_tables, pg_stat_user_tables, and pg_stat_sys_tables.</p><p>The scan counters tell you how the table is being accessed.</p><p>seq_scan is the number of sequential scans, while seq_tup_read tells you how many rows those scans read.</p><p>Then idx_scan tells you the number of index scans and idx_tup_fetch tells you how many rows were fetched through indexes.</p><p>If a large table has a huge number of sequential scans compared with index scans, that is at least a reason to investigate whether an index is missing.</p><h3>Table Write Activity</h3><p>The same view also tells you about writes.</p><p>n_tup_ins counts inserted rows, n_tup_upd counts updated rows, and n_tup_del counts deleted rows.</p><p>Then there are two counters that become interesting when thinking about bloat.</p><p>n_tup_hot_upd counts updates that qualified for HOT, or Heap-Only Tuple updates. These are cheaper because they don&#39;t require changes to indexes.</p><p>n_tup_newpage_upd counts updates that needed a new page, which is the more expensive opposite of HOT.</p><h3>Live Rows, Dead Rows &amp; Analyze</h3><p>n_live_tup is an estimate of the number of live rows in the table, while n_dead_tup estimates the dead rows — rows created by updates or deletes that haven&#39;t been cleaned up by vacuum yet.</p><p>There is also n_mod_since_analyze, which counts how many rows have been modified since the last ANALYZE. This can tell you whether your planner statistics might be getting stale.</p><p>Then you have the maintenance history: last_vacuum, last_autovacuum, last_analyze, and last_autoanalyze, along with vacuum_count and autovacuum_count.</p><p>This gives us some very practical signals.</p><p>If a large table has lots of sequential scans, investigate missing indexes.</p><p>If n_dead_tup is becoming large relative to n_live_tup, autovacuum may not be keeping up.</p><p>If a high-write table hasn’t been auto-vacuumed for a long time, look at its autovacuum_vacuum_scale_factor and autovacuum_vacuum_threshold.</p><p>And if the ratio of HOT updates is low, the updates may be touching indexed columns or the pages may not have enough free space for HOT updates, which can contribute to more bloat.</p><p>A useful query for getting a quick picture of this is:</p><pre>SELECT relname, seq_scan, idx_scan, n_live_tup, n_dead_tup,<br>       round(n_dead_tup::numeric / nullif(n_live_tup,0), 3) AS dead_ratio,<br>       last_autovacuum<br>FROM pg_stat_user_tables<br>ORDER BY n_dead_tup DESC;</pre><h3>pg_stat_all_indexes</h3><p>Now let’s talk about indexes.</p><p>pg_stat_all_indexes gives you one row per index and helps answer one very important question:</p><blockquote><em>Is this index actually being used?</em></blockquote><p>idx_scan tells you how many index searches have been performed.</p><p>idx_tup_read tells you how many index entries or pointers Postgres looked at inside the index.</p><p>And idx_tup_fetch tells you how many actual live table rows were fetched using that index.</p><p>You can think of the difference as:</p><p><strong>idx_tup_read: how many index entries did Postgres inspect?</strong></p><p><strong>idx_tup_fetch: how many actual rows did it go and fetch?</strong></p><h3>Why Are idx_tup_read And idx_tup_fetch Different?</h3><p>You might expect these numbers to be equal, but they aren’t.</p><p>One reason is MVCC and dead rows. The index can point to a row, but when Postgres visits the table it can discover that the row is no longer visible because it was updated or deleted by another transaction. So the index entry was read, but a valid row wasn’t fetched.</p><p>The other major reason is index-only scans. If a query can get everything it needs directly from the index, Postgres doesn’t need to visit the table at all.</p><p>For example:</p><pre>SELECT id FROM users WHERE id = 5;</pre><p>In that situation, idx_tup_read can increase while idx_tup_fetch stays low or even at zero.</p><h3>Bitmap Scans Are A Special Case</h3><p>Bitmap scans make this slightly more complicated.</p><p>Postgres can combine results from multiple indexes using AND/OR operations. Because those results are combined, it becomes difficult to attribute the individual heap-row fetches back to one specific index.</p><p>During a bitmap scan, idx_tup_read is incremented for the indexes involved, and the table&#39;s idx_tup_fetch is incremented, but the individual index-level idx_tup_fetch isn&#39;t affected.</p><h3>Why Can idx_scan Be Higher Than Expected?</h3><p>Another thing that can surprise you is idx_scan.</p><p>A single query execution can trigger multiple index searches. A query such as:</p><pre>WHERE col IN (1, 2, 3)</pre><p>can result in multiple index searches. An OR chain can also be transformed into an array operation, and B-tree skip scans can reposition within the index multiple times.</p><p>So idx_scan can sometimes be much higher than the number of actual query executions.</p><p>If you need the exact number of index searches performed by a scan node, EXPLAIN ANALYZE is the better tool because it shows the total number of searches associated with that scan node.</p><p>You can inspect index usage with:</p><pre>SELECT relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch<br>FROM pg_stat_user_indexes<br>ORDER BY idx_scan ASC;</pre><p>An index with idx_scan = 0, or extremely low usage on a non-trivial table, can be a candidate for dropping because even an unused index still creates write overhead on inserts and updates.</p><h3>pg_statio_all_tables</h3><p>pg_statio_all_tables has a similar per-table structure, but now the focus is specifically I/O.</p><p>It tells you how often the table’s data and indexes were found in cache versus how often they actually had to be read from disk.</p><p>heap_blks_read and heap_blks_hit refer to the table&#39;s own data pages.</p><p>idx_blks_read and idx_blks_hit represent the combined I/O for the table&#39;s indexes.</p><p>And then there are toast_blks_read and toast_blks_hit for TOAST data, which is where Postgres stores large values outside the main table.</p><h3>But Why Does An Index Need A Disk Read?</h3><p>You might think an index is supposed to make lookups faster, so why would an index itself need to read from disk?</p><p>Because the index is also a physical data structure stored on disk.</p><p>For a B-tree lookup, Postgres still has to read the relevant B-tree pages into memory so that it can walk through the tree and find the matching rows.</p><p>So there are actually two different sets of pages involved.</p><p>The index pages help Postgres figure out <strong>where</strong> the matching rows are, while the heap/table pages contain the actual row data that Postgres may need to fetch.</p><p>An index-only scan can skip the table access, but the index itself can still require disk reads if its pages aren’t currently cached.</p><p>You can get a simple picture of table cache behaviour with:</p><pre>SELECT relname,<br>       heap_blks_hit, heap_blks_read,<br>       round(heap_blks_hit::numeric<br>             / nullif(heap_blks_hit + heap_blks_read, 0), 4)<br>             AS heap_hit_ratio<br>FROM pg_statio_user_tables<br>ORDER BY heap_blks_read DESC;</pre><p>For hot OLTP tables, around 99%+ hit ratio is a common target. If the hit ratio is low while disk reads are high, it can indicate that the table’s working set doesn’t fit into shared_buffers.</p><h3>Part Five — I/O, Buffers &amp; Background Writers</h3><p>Now we are getting into the deepest and most mechanical part of Postgres monitoring.</p><p>This is basically the layer where we ask:</p><p><em>Is my cache actually working?</em></p><p>and:</p><p><em>Is my disk keeping up?</em></p><h3>pg_stat_io</h3><p>pg_stat_io gives us a detailed picture of I/O operations, including reads, writes, and related activity.</p><p>Instead of simply telling you “Postgres read some data”, it breaks the information down by who performed the I/O and what kind of I/O it was.</p><p>Each row represents a combination of:</p><p>backend_type + object + context</p><p>The backend_type tells us who is doing the work.</p><p>A client backend is a normal connection executing queries.</p><p>An autovacuum worker is doing background vacuum work.</p><p>The background writer is flushing dirty pages.</p><p>The checkpointer is doing checkpoint I/O.</p><p>And the walwriter is writing WAL.</p><p>This distinction is useful because it lets you separate very different situations. You can ask whether autovacuum is generating a large amount of read I/O or whether normal client queries are missing the cache.</p><p>Then there is the object being touched.</p><p>relation means normal tables and indexes.</p><p>temp relation means temporary tables.</p><p>wal means the Write-Ahead Log.</p><p>And the context tells you how the I/O happened.</p><p>normal is the usual path through shared buffers.</p><p>vacuum is vacuum/analyze I/O outside the normal buffer pool.</p><p>bulkread and bulkwrite are used for large sequential scans and operations such as COPY, helping them avoid destroying the normal cache.</p><p>A useful query is:</p><pre>SELECT backend_type, object, context, reads, writes, read_time, write_time<br>FROM pg_stat_io<br>WHERE reads &gt; 0 OR writes &gt; 0<br>ORDER BY reads DESC;</pre><p>One important detail: read_time and write_time stay at zero unless track_io_timing is enabled.</p><h3>Understanding The pg_stat_io Counters</h3><p>The individual counters are useful once you know what they represent.</p><p>hits means a needed block was already found in a shared buffer.</p><p>evictions means a block was written out of a buffer to make room for another use.</p><p>reuses refers to an existing buffer being reused inside the size-limited ring buffer used for bulkread, bulkwrite, and vacuum operations.</p><p>fsyncs counts fsync() calls, and this is tracked only in the normal context.</p><h3>Why Does A Bulk Operation Need Its Own Ring Buffer?</h3><p>Imagine a huge sequential scan.</p><p>If Postgres treated that scan like every other query and loaded thousands of pages into the normal shared_buffers, it could completely trash the cache.</p><p>You could run one giant SELECT * and suddenly evict the hot pages that all your other queries depend on.</p><p>That is why bulk operations get a small, fixed-size ring buffer outside the main pool.</p><p>Pages are read into this small ring and the same slots are repeatedly reused. This keeps the footprint of the bulk operation small and protects the rest of shared_buffers from a one-time giant scan.</p><p>This also explains the slightly confusing meaning of evictions in this context. It doesn&#39;t mean that a page was simply kicked out of shared_buffers to make room for another page in shared_buffers. It means a page was pulled out of shared buffers specifically so that the bulk operation could use its separate ring buffer.</p><p>And reuses tells you how often those existing ring slots are being reused. Once the ring is full, the next page can reuse an existing slot instead of allocating another one. So a high reuse count can actually mean that the ring buffer is doing exactly what it is supposed to do.</p><h3>Is fsync Really A Forced Write To Disk?</h3><p>Yes.</p><p>A write can simply land in the operating system’s cache without being physically durable yet.</p><p>fsync() is the operation that forces the storage system to persist the data and confirm that persistence.</p><p>That makes fsyncs a useful signal for disk-write cost. If you see high fsync counts together with high write_time, storage may be becoming a bottleneck.</p><h3>pg_stat_bgwriter</h3><p>The background writer is responsible for cleaning up dirty pages by writing them to disk during normal operation.</p><p>pg_stat_bgwriter gives us metrics for that process.</p><p>buffers_clean tells us how many memory pages were written to disk by the background writer during routine cleanup.</p><p>maxwritten_clean tells us how many times the background writer had to stop its cleanup scan early because it hit the maximum number of pages it was allowed to write in that round.</p><p>buffers_alloc tells us how many times a buffer slot had to be allocated to load new data into memory.</p><p>And, just like with the other cumulative counters, stats_reset tells us when the counters were last reset so that we can calculate meaningful rates.</p><h3>maxwritten_clean — The Warning Light</h3><p>Ideally, maxwritten_clean should remain zero or very low compared with the amount of time the system has been running.</p><p>If it is steadily or rapidly increasing, the background writer is repeatedly failing to keep up with incoming dirty pages.</p><p>Possible actions include increasing bgwriter_lru_maxpages or reducing bgwriter_delay.</p><h3>What Does buffers_alloc Tell Us?</h3><p>A high buffers_alloc rate means the database is frequently loading data into memory that wasn&#39;t already cached.</p><p>That can happen because of heavy read workloads, full table scans, or because the active working set is larger than shared_buffers.</p><p>A low rate generally means Postgres is getting more benefit from the data already in memory and is not constantly needing fresh buffer allocations.</p><p>There is also an interesting comparison between buffers_clean and buffers_alloc.</p><p>buffers_clean tells you about pages written by the background writer, while buffers_alloc represents buffer allocations requested by backends.</p><p>If the background writer is doing very little compared with the overall activity, it can mean that backends or the checkpointer are doing most of the disk writes and the background writer isn’t being used much.</p><p>But there is an even more direct warning signal.</p><h3>buffers_backend — A More Direct Red Flag</h3><p>buffers_backend represents pages that backend processes had to write themselves because the background writer or checkpointer didn&#39;t get there in time.</p><p>This is often a more direct red flag than maxwritten_clean.</p><p>Why?</p><p>Because now the process actually serving your query is the one doing the disk write.</p><p>And if a query-serving backend has to stop what it is doing and write dirty pages itself, the query can stall.</p><p>So if buffers_backend is consistently high, that is a strong signal that the background writing/checkpointing system isn&#39;t keeping up with the workload.</p><h3>Part Six — Replication</h3><p>Finally, let’s talk about replication.</p><p>At a high level, a primary server generates changes and a standby or replica receives them.</p><p>Physical replication works at the whole-cluster level, while logical replication gives you more control over which tables or changes are replicated.</p><p>The monitoring views are slightly different depending on which side of the replication connection you are looking at.</p><h3>pg_stat_replication</h3><p>On the primary, pg_stat_replication gives you one row for each connected standby.</p><p>This is where you can see how far behind each replica is using things like:</p><p>flush_lag, replay_lag , write_lag</p><p>and you can also see the current replication state, such as streaming or catchup.</p><p>So if your question is:</p><p><em>“Are my replicas keeping up with the primary?”</em></p><p>this is one of the first views you want to check.</p><h3>pg_stat_replication_slots</h3><p>Also on the primary, pg_stat_replication_slots gives you statistics about logical replication slots.</p><p>It tells you things such as how much decoding data was spilled to disk or streamed, which can be useful when tuning logical_decoding_work_mem.</p><h3>pg_stat_wal_receiver</h3><p>Now move over to the standby.</p><p>pg_stat_wal_receiver tells you what the standby is receiving from the primary, including information such as the last WAL location received and flushed.</p><p>You can think of it as the standby-side counterpart to pg_stat_replication.</p><h3>pg_stat_recovery_prefetch</h3><p>pg_stat_recovery_prefetch is also a standby-side view.</p><p>It tells you how well WAL block prefetching is working during crash recovery and WAL replay, including how many prefetches were useful versus how many were actually needed.</p><p>This becomes useful when you are trying to understand how efficiently a standby is catching up and replaying WAL.</p><h3>Logical Replication</h3><p>For logical replication, the subscriber has its own views.</p><p>pg_stat_subscription shows the worker processes handling logical replication and their progress.</p><p>Then pg_stat_subscription_stats gives you errors and conflicts during logical replication, including things such as unique constraint violations and missing rows.</p><p>So if you’re asking: <em>“Is logical replication silently failing?”</em></p><p>this is the place to look.</p><p>The easiest mental model is:</p><p><strong>Primary:</strong> pg_stat_replication + pg_stat_replication_slots → &quot;How are my replicas doing?&quot;</p><p><strong>Standby:</strong> pg_stat_wal_receiver + pg_stat_recovery_prefetch → &quot;How am I receiving and catching up?&quot;</p><p><strong>Logical subscriber:</strong> pg_stat_subscription + pg_stat_subscription_stats → &quot;How is logical replication behaving on the subscriber?&quot;</p><p>This isn’t directly relevant to Catfish itself because Catfish is a connection pooler rather than a replication system, but if the Postgres server behind the pooler is replicated, these views become important.</p><h3>So… What Do I Actually Look At When Something Goes Wrong?</h3><p>At this point, there are a lot of views.</p><p>And I know what you’re probably thinking: <em>“Am I really supposed to remember all of these?”</em></p><p>No.</p><p>You don’t need to memorize every column in every pg_stat_* view.</p><p>What matters is having a mental path through the system.</p><p>If something is slow <strong>right now</strong>, start with pg_stat_activity. Look at the state, query, duration, and wait event.</p><p>If the wait event says Lock, move to pg_locks and find out who is holding the lock.</p><p>If commits suddenly feel slow, look at pg_stat_wal and investigate WAL sync time and full-page-image behaviour. Then check pg_stat_checkpointer to see whether checkpoints are happening too frequently.</p><p>If disk I/O looks suspicious, move to pg_stat_io and pg_stat_bgwriter. Ask who is actually doing the I/O and whether backend processes are being forced to write dirty pages themselves.</p><p>If one table looks unhealthy, use pg_stat_all_tables. Look at sequential scans, index scans, dead rows, autovacuum history, and modifications since ANALYZE.</p><p>If an index looks suspicious, use pg_stat_all_indexes and check whether it is actually being used.</p><p>If cache behaviour looks wrong, use pg_statio_all_tables and pg_stat_io to separate cache hits from real disk reads.</p><p>And if you have replicas, use the replication views on the primary and standby to understand lag and replay behaviour.</p><p>That is the actual value of all these statistics.</p><p>Not memorizing them.</p><p>Knowing <strong>which one to reach for next</strong>.</p><h3>One Last Thing — These Numbers Are Not Your History</h3><p>There is one idea I want to come back to because it applies to almost everything we discussed.</p><p>Most of these pg_stat_* values are not a historical record.</p><p>They are counters and snapshots that tell you what has happened since the last reset.</p><p>If the database restarts or you reset the counters, the historical information in those counters can disappear.</p><p>So if you actually care about how your Postgres server behaves over days, weeks, and months, you shouldn’t rely on manually running these queries whenever something breaks.</p><p>You should scrape them.</p><p>Store them.</p><p>Graph them.</p><p>A setup such as Prometheus + postgres_exporter gives you exactly that. Instead of looking at a raw number and saying:</p><blockquote><em>“wal_bytes is 500 GB.”</em></blockquote><p>you can look at the graph and say:</p><blockquote><em>“WAL generation increased by 120 MB/s during that deployment.”</em></blockquote><p>And that second statement is much more useful.</p><p>Because now you have context.</p><p>You can compare it with traffic.</p><p>You can compare it with checkpoints.</p><p>You can compare it with disk I/O.</p><p>You can compare it with commit latency.</p><p>And suddenly a metric becomes an explanation rather than just a number.</p><h3>The Big Picture</h3><p>After going through all of this, Postgres monitoring might look like a huge collection of unrelated statistics.</p><p>But they actually form a pretty clean picture.</p><p>The <strong>activity views</strong> tell you what is happening right now and, when something is stuck, what it is waiting for.</p><p>The <strong>WAL and checkpoint statistics</strong> show you how Postgres is making changes durable and how that durability work interacts with disk I/O and commit latency.</p><p>The <strong>database, table, and index statistics</strong> tell you whether your workload, schema, indexes, and vacuum configuration are behaving the way you expect.</p><p>The <strong>I/O and buffer statistics</strong> tell you whether your cache is actually earning its keep and whether your storage system can keep up with the amount of work Postgres is asking it to do.</p><p>And the <strong>replication statistics</strong> tell you whether your replicas are receiving, flushing, and replaying changes properly.</p><p>More importantly, these things are connected.</p><p>A slow commit can lead you to WAL. WAL can lead you to checkpoints. Checkpoints can lead you to disk I/O. Disk I/O can lead you to buffer behaviour.</p><p>A slow query can lead you to pg_stat_activity.</p><p>A wait event can lead you to a lock. A table with too many dead tuples can lead you to autovacuum. An unused index can lead you to a schema decision. And a replica falling behind can lead you through WAL receiver and replay statistics.</p><p>That, to me, is what good database monitoring actually means.</p><p>It isn’t about looking at a hundred numbers and deciding whether each one is “high” or “low”. It is about starting with a symptom and following the chain until you find the thing actually causing it. Because at the end of the day, monitoring isn’t really about collecting metrics. It is about being able to answer questions.</p><p><em>Why is Postgres slow?</em></p><p><em>What changed?</em></p><p><em>Why did WAL suddenly spike?</em></p><p><em>Why are commits taking longer?</em></p><p><em>Why is autovacuum falling behind?</em></p><p><em>Why are replicas lagging?</em></p><p><em>Why is my disk suddenly doing so much work?</em></p><p>Once you have the right statistics, collected over time, those questions stop being guesses. You can actually follow the evidence. And that is when monitoring becomes useful. Because you’re no longer just watching your Postgres serve<strong>r</strong>. You’re actually understanding what it is doing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22367f559dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything About Your Postgres Server Monitoring —part. I]]></title>
            <link>https://medium.com/@shekdivyanshu/everything-about-your-postgres-server-monitoring-part-i-b3d0a974981c?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d0a974981c</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 18:14:58 GMT</pubDate>
            <atom:updated>2026-08-22T18:14:58.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOs4IegMg6Iz1W3gN0-VYg.png" /></figure><p>What gets measured is what gets improved.</p><p>This holds for humans and holds even better for machines. And your Postgres server could be the single most important part of your system. So how do we actually measure how good our database is doing? How do we know if it is healthy, if it is struggling, or if something that looks scary is actually completely normal?</p><p>This blog will answer that for you.</p><p>Its going to be a long one, so take your time!</p><p>We are going to go from the basics of how Postgres statistics work, all the way to connections, wait events, WAL, checkpoints, archiving, tables, indexes, I/O, buffers, background writers, and finally replication.</p><p>And I don’t just want to explain what each metric means. The more important question is what that metric actually tells you when you are debugging a real database.</p><h3>Before Everything Else — How Does Postgres Statistics Actually Work?</h3><p>The numbers you see in Postgres statistics views are not all the same kind of numbers. Some of them are meant to tell you what is happening right now, while others are cumulative counters that keep increasing as the database does more work.</p><h4>The Two Kinds Of Statistics Views</h4><p>The first type is what we can think of as <strong>dynamic statistics</strong>. These are meant to tell you what is happening right now. pg_stat_activity is probably the most important example, along with the pg_stat_progress_* views. If you are debugging something that is currently stuck, running for too long, or behaving strangely, these are the kinds of views you want to look at.</p><p>The second type is <strong>collected or cumulative statistics</strong>. These are counters that build up over time, usually since the last statistics reset. Views such as pg_stat_database, pg_stat_bgwriter, and pg_stat_all_tables fall into this category.</p><p>So the simple rule of thumb is: if something is stuck <strong>right now</strong>, dynamic views are usually what you want. If you are trying to understand trends, bloat, cache effectiveness, or workload behaviour over time, cumulative statistics are much more useful.</p><p>But there is another thing we need to understand before trusting these numbers blindly.</p><h4>The Numbers Aren’t Always Instant</h4><p>Postgres does not necessarily update every statistics counter immediately.</p><p>Each process waits until it is about to become idle before pushing its statistics into shared memory, and it will not do that more than once per second. So if a query is still running, some of the statistics associated with that activity may not have been flushed yet.</p><p>This is one reason why statistics can sometimes look slightly behind reality.</p><p>There is an important exception here though. The information in pg_stat_activity about the query that is currently running is always live because that information is collected differently through track_activities.</p><p>So if you are looking at pg_stat_activity to answer &quot;what query is running right now?&quot;, that particular information is not subject to the same delay.</p><h4>Statistics Can Also Freeze Inside A Transaction</h4><p>This is another little detail that can be confusing when you first start working with Postgres monitoring.</p><p>Once you look at statistics inside a transaction, Postgres can keep showing you the same statistics snapshot for the rest of that transaction. The numbers can actually change in the database underneath you, but your transaction can continue seeing the same snapshot.</p><p>This is intentional because it keeps your statistics queries internally consistent. But it can be confusing if you run a statistics query, let some database activity happen, and then run the same query again inside the same transaction and get exactly the same numbers.</p><p>You might think Postgres isn’t updating the statistics.</p><p>It is. You are just still looking at the same snapshot.</p><p>If you want to avoid this, the simplest option is to not wrap these monitoring checks inside an explicit transaction. You can also force a refresh using:</p><pre>SELECT pg_stat_clear_snapshot();</pre><p>There are also two related settings worth knowing about. stats_fetch_consistency = snapshot gives you a fully consistent snapshot, although it uses more memory, while stats_fetch_consistency = none disables this caching behaviour and can be useful for one-off checks.</p><h4>What If I Want To See My Own Uncommitted Activity?</h4><p>There is actually another set of statistics views for this.</p><p>If you want to see what the current transaction itself has done, including activity that hasn’t been flushed into the normal statistics yet, you can use the transaction-level views:</p><ul><li>pg_stat_xact_all_tables</li><li>pg_stat_xact_sys_tables</li><li>pg_stat_xact_user_table</li><li>pg_stat_xact_user_functions</li></ul><p>These update continuously for the current transaction and are useful when you specifically want to inspect your own uncommitted activity.</p><h4>Permissions Matter Too</h4><p>There is one more thing that can make monitoring confusing: permissions.</p><p>An ordinary Postgres user can see the full information for its own sessions, but when looking at other sessions, many columns can come back as NULL. The session itself is still visible, but some of the information about it is hidden.</p><p>Superusers and members of pg_read_all_stats can see everything.</p><p>This is worth remembering if you are building something like a monitoring system or a connection pooler that connects to Postgres using a non-superuser role. You might query pg_stat_activity and wonder why certain columns are empty. The problem may not be with Postgres at all. Your monitoring user may simply not have permission to see that information.</p><h3>Resetting Statistics — What Does It Actually Do?</h3><p>Now let’s talk about resetting statistics.</p><p>There are situations where having a clean baseline is useful. Imagine you change a configuration setting, maybe increase shared_buffers, retune autovacuum, or change some other database setting. If you keep the old accumulated counters, comparing the numbers before and after the change can become messy.</p><p>Resetting the statistics gives you a clean starting point.</p><p>But there is one very important thing to understand.</p><p><strong>Resetting statistics is not a rebuild.</strong></p><p>Postgres does not recalculate anything when you reset statistics. It doesn’t scan your tables and it doesn’t rebuild anything. It simply zeroes the monitoring counters.</p><p>If idx_blks_read was sitting at 50,000, after a reset it becomes 0 and starts counting new activity from there. The old number is gone. It isn&#39;t archived somewhere and it isn&#39;t subtracted later.</p><p>The reset itself is also extremely cheap. It is essentially just zeroing counters in shared memory, so there is no table scan, no meaningful disk I/O, and no significant lock contention involved.</p><h3>Monitoring Statistics Are Not Planner Statistics</h3><p>This distinction is important because the word “statistics” makes these things sound related when they actually serve different purposes.</p><p>Resetting pg_stat_* and pg_statio_* only affects monitoring and activity counters. It does <strong>not</strong> reset pg_stats or pg_statistic, which contain the planner statistics generated by ANALYZE.</p><p>Refreshing planner statistics is a separate operation, and unlike resetting monitoring counters, ANALYZE isn&#39;t free because it actually scans the table to collect information for the query planner.</p><h3>The Different Statistics Reset Functions</h3><p>Postgres gives us a few different reset functions depending on how much you want to clear.</p><p>pg_stat_reset() resets all statistics for the current database, including table, index, and function statistics.</p><p>pg_stat_reset_shared(target) handles cluster-wide shared statistics. The targets include archiver, bgwriter, checkpointer, io, recovery_prefetch, wal, and all.</p><p>If you only care about a specific object, there are more targeted options. pg_stat_reset_single_table_counters(oid) resets the counters for one table, while pg_stat_reset_single_function_counters(oid) does the same thing for one function. There are also pg_stat_reset_slru(name) for SLRU statistics, pg_stat_reset_replication_slot(name) for one replication slot, and pg_stat_reset_subscription_stats(oid) for subscription error and conflict statistics.</p><h3>Should You Actually Reset Statistics In Production?</h3><p>Usually, not really.</p><p>And the reason is simple: Postgres statistics are not your historical monitoring database. They are a live/cumulative view of what has happened since the last reset.</p><p>If Postgres restarts uncleanly or you manually reset the counters, that history is gone.</p><p>So if you actually want to understand how your database behaves over time, manually resetting counters is not the solution.</p><p>You should collect them somewhere else.</p><h3>The Right Way To Monitor Postgres</h3><p>In a real monitoring setup, an agent periodically scrapes the Postgres statistics views, usually every 10–60 seconds, and sends those values to a time-series database.</p><p>A very common open-source combination is <strong>Prometheus + postgres_exporter</strong>, with Grafana used for visualization. There are also managed tools such as Datadog and New Relic, and Postgres-specific tools such as pganalyze that go deeper into query-level analysis.</p><p>But here is the important part.</p><p>Most of these statistics are cumulative counters.</p><p>Suppose Postgres tells you that it has performed 500,000 reads.</p><p>That number doesn’t tell you very much on its own.</p><p>Your monitoring system can scrape it now and then scrape it again 30 seconds later. If the value went from 499,500 to 500,000, then you know that 500 reads happened in those 30 seconds.</p><p>That is a rate.</p><p>And that rate is what you actually want to graph.</p><p>So instead of graphing the raw ever-growing counter, monitoring systems calculate the difference between two scrapes and turn it into something like reads per second.</p><p>This is also why you almost never need to manually reset statistics in a properly monitored production system. Your monitoring system is already calculating deltas regardless of how large the raw counters become. Manual resets are mostly useful for quick tuning sessions when you are experimenting with something and want a clean baseline.</p><h3>What About A Connection Pooler?</h3><p>If you are building something like Catfish, you don’t necessarily want to expose every single Postgres statistic yourself.</p><p>A much more useful pattern is to expose a /metrics endpoint with the metrics that belong to the pooler itself.</p><p>Things like active connections, queue depth, and backpressure state can be exposed in Prometheus format. Then they can be monitored alongside the actual Postgres metrics.</p><p>This gives you another useful distinction. If users are experiencing slow queries, you can start asking whether Postgres is actually slow or whether the pooler is under pressure and is the thing holding requests up.</p><h3>So How Do You Know If A Number Is High Or Low?</h3><p>This is probably one of the most important questions in monitoring.</p><p>And unfortunately, there is no universal threshold for most Postgres metrics.</p><p>Take a counter of 500,000 fsyncs. Is that bad?</p><p>It depends.</p><p>If those 500,000 fsyncs happened in five minutes, that could be alarming. If they happened over three months, it could be completely normal.</p><p>The first thing you should look at is the <strong>rate over time</strong>, not the raw count. You should always consider how much time has passed since stats_reset.</p><p>The second thing is your own baseline. Every workload is different, and your hardware, query patterns, traffic, and data size all affect what “normal” looks like. A deviation from your own normal behaviour is often more useful than some generic number someone gave you on the internet.</p><p>The third thing is ratios. For example, the cache hit ratio can be calculated as:</p><pre>hits / (hits + reads)</pre><p>Around 99% or higher is a common rule of thumb for OLTP workloads, although analytics workloads that scan large tables can naturally have lower hit ratios.</p><p>And finally, always correlate a metric with an actual symptom. A high number by itself isn’t automatically a problem. If disk reads are high but queries are fast, users aren’t complaining, and OS-level disk latency is healthy, then the number may simply be normal for your workload.</p><h3>Part Two — Connections, Activity &amp; Wait Events</h3><p>Now we get into the part of Postgres monitoring that is probably the most useful when something is actively going wrong.</p><p>What is every connection doing right now?</p><p>And if one of them is stuck, <strong>why</strong> is it stuck?</p><p>This is where pg_stat_activity becomes one of the most important views you should know.</p><h3>pg_stat_activity</h3><p>pg_stat_activity gives you one row per backend process, which you can roughly think of as one row per connection or worker doing something.</p><p>It tells you who is connected, what they are doing, what state they’re in, and whether they are currently waiting for something.</p><p>The simplest version is:</p><pre>SELECT pid, usename, state, query, query_start<br>FROM pg_stat_activity;</pre><p>That is already useful, but when debugging a real issue, we usually want more information.</p><p>For example, to find long-running or stuck queries:</p><pre>SELECT pid, usename, state, wait_event_type, wait_event,<br>       now() - query_start AS running_for, query<br>FROM pg_stat_activity<br>WHERE state != &#39;idle&#39;<br>ORDER BY running_for DESC;</pre><p>This gives you the running duration and the wait information, which is often where the real clue is.</p><h3>Finding Idle-in-Transaction Connections</h3><p>There is another query that is especially useful when working with a connection pooler:</p><pre>SELECT pid, usename, state,<br>       now() - xact_start AS idle_txn_duration,<br>       query<br>FROM pg_stat_activity<br>WHERE state = &#39;idle in transaction&#39;<br>ORDER BY idle_txn_duration DESC;</pre><p>So what exactly is the difference between idle and idle in transaction?</p><h3>idle vs idle in transaction</h3><p>An idle connection is usually completely normal. The connection is open, the application isn&#39;t currently doing anything, and there is no transaction open. It is simply sitting there waiting for the next command.</p><p>idle in transaction is very different.</p><p>It means the application started a transaction, ran one or more commands, and then hasn’t committed or rolled back yet. Postgres is essentially waiting for the application to finish the transaction.</p><p>And this matters much more than a normal idle connection because that open transaction can continue holding resources.</p><p>While a connection sits idle inside a transaction, it can hold active table locks and prevent autovacuum from cleaning up old row versions. If this continues for long enough, it can slow down the whole database.</p><p>There is also another way to end up in this state. A transaction can start, one of its queries can fail, and the application can fail to roll the transaction back. Postgres then stops accepting normal queries in that session until the transaction is aborted, while the session can still hold its locks and other resources.</p><p>So a simple application error can turn into a database-wide problem if the application doesn’t clean up its transaction properly.</p><h3>Will Postgres Disconnect Idle Connections Automatically?</h3><p>Not necessarily.</p><p>A completely idle connection can remain open indefinitely unless something else, such as a proxy, load balancer, firewall, or client-side TCP keepalive configuration, closes it.</p><p>For connections that are specifically stuck in a transaction, Postgres provides:</p><p>idle_in_transaction_session_timeout</p><p>which automatically terminates sessions that stay idle in a transaction for longer than the configured duration.</p><p>There is also:</p><p>idle_session_timeout</p><p>which terminates idle sessions generally, whether they are inside or outside a transaction.</p><h3>Wait Events — The Most Useful Part Of pg_stat_activity</h3><p>Now suppose a backend is active, but it isn’t actually making progress.</p><p>The state tells you the broad picture, but wait_event_type and wait_event can tell you what the backend is waiting for.</p><p>You can find currently waiting sessions with:</p><pre>SELECT pid, wait_event_type, wait_event, state, query<br>FROM pg_stat_activity<br>WHERE wait_event IS NOT NULL;</pre><p>The important thing here isn’t memorizing every individual wait event. It is understanding the categories.</p><p>Activity usually means an internal background process is waiting in its own loop for work. That&#39;s generally normal.</p><p>BufferPin means a process is waiting for exclusive access to a data page that another process is holding, such as through a cursor.</p><p>Client means Postgres is waiting on the application itself. If you see lots of ClientRead while sessions are marked active, the application may be the slow part rather than Postgres.</p><p>Extension means the wait is happening inside a third-party extension.</p><p>IO means the process is waiting for actual disk I/O, which can point toward slow storage.</p><p>IPC means it is waiting for another Postgres process, such as a parallel worker or checkpoint coordination.</p><p>Lock means a heavyweight lock is involved — table locks, row locks, advisory locks, and similar things. This is one of the first things to investigate when you suspect blocking.</p><p>LWLock means Postgres is waiting for an internal lightweight lock protecting shared memory, which is generally internal contention rather than application-level blocking.</p><p>And Timeout means the backend is waiting on a timer, such as with pg_sleep() or deliberate vacuum throttling.</p><p>You don’t need to memorize every specific wait event.</p><p>The workflow is much simpler: check pg_stat_activity, find the active session, see what wait_event says, and then investigate that specific wait. If the wait is Lock, the natural next step is joining against pg_locks to find who is holding the lock.</p><p>So the mental model is basically:</p><p><strong>activity stats tell you about the connection → state tells you whether it is active or idle → wait event tells you why an active connection is stuck.</strong></p><h3>Part Three — WAL, Checkpoints &amp; Archiving</h3><p>Now we get into the durability engine underneath Postgres.</p><p>This is where WAL, checkpoints, disk I/O and backups all connect together. Understanding this part is especially useful because things like slow commits, growing WAL files, and long recovery times can often be traced back to the same chain of events.</p><h3>What Is A WAL Segment?</h3><p>WAL stands for <strong>Write-Ahead Log</strong>, and it is basically Postgres’s transaction log.</p><p>The fundamental idea is that before a change is applied to the actual table data, the change is first written to WAL. That way, if the server crashes halfway through a write, Postgres can replay the WAL during recovery and reconstruct the changes that had already been committed.</p><p>The WAL isn’t stored as one giant file. It is divided into segments, and by default each segment is 16 MB. The segment size is set during cluster initialization using --wal-segsize, and it cannot be changed after the cluster has been created.</p><p>As transactions generate WAL, Postgres writes into the current segment. Once that segment fills up, it moves to another one. You can think of it as a rotating log file.</p><h3>What Exactly Is A Checkpoint?</h3><p>A checkpoint is basically a guarantee point.</p><p>It means that all the WAL up to that point has now been reflected in the actual data files on disk. Postgres takes dirty pages — modified pages that were sitting in shared_buffers — and flushes them to the actual table and index files.</p><p>Why does this matter?</p><p>Because during crash recovery, Postgres only needs to replay WAL generated <strong>after the last checkpoint</strong>. Everything before that checkpoint has already been written into the real data files.</p><p>This is also connected to WAL segment recycling. Once a checkpoint completes, WAL segments older than the checkpoint are no longer needed for crash recovery and can potentially be recycled.</p><p>But there are exceptions. If archiving hasn’t successfully backed up a segment, Postgres can’t recycle it when archiving is enabled. A standby or replication slot can also keep an older WAL segment around because it still needs that history.</p><h3>The Checkpoint Tradeoff</h3><p>Checkpoint tuning is basically a tradeoff.</p><p>If checkpoints happen too often, Postgres constantly has to produce bursts of disk writes, which can hurt performance.</p><p>But if checkpoints happen too rarely, crash recovery takes longer and more WAL can accumulate on disk while waiting to become recyclable.</p><p>This is why settings such as checkpoint_timeout and max_wal_size matter so much. They influence how frequently checkpoints happen and how much WAL can accumulate before Postgres needs to force another checkpoint.</p><h3>write() Is Not The Same As fsync()</h3><p>There is another distinction that becomes important when looking at disk performance.</p><p>The rough path looks like this:</p><pre>write()<br>    ↓<br>data leaves Postgres<br>    ↓<br>OS RAM / buffer cache<br>    ↓<br>fsync()<br>    ↓<br>physically durable on disk</pre><p>When Postgres writes dirty pages, those pages first move from Postgres’s own memory into the operating system’s buffer cache. That handoff is relatively fast, but it doesn’t necessarily mean the data is physically durable against a power failure.</p><p>fsync() is what forces the storage system to actually persist the data and confirm it.</p><p>That confirmation is what allows Postgres to consider the commit safely durable.</p><h3>pg_stat_checkpointer</h3><p>pg_stat_checkpointer tracks checkpoint activity across the cluster, and it has one row.</p><p>The first counters worth knowing are num_timed, which counts checkpoints triggered because checkpoint_timeout was reached, and num_requested, which counts checkpoints triggered manually or because too much WAL was generated and max_wal_size was reached.</p><p>num_done tells you how many checkpoints actually completed.</p><p>On standby servers, you also get the corresponding restartpoint counters: restartpoints_timed, restartpoints_req, and restartpoints_done.</p><p>There are also performance metrics.</p><p>write_time is the time spent copying dirty pages to the OS, while sync_time is the time spent doing fsync() and forcing physical durability. buffers_written tells you how many memory blocks were written during checkpoints.</p><p>A healthy system should generally have num_timed dominating over num_requested. If num_requested keeps increasing, checkpoints are being forced earlier than expected because the workload is generating WAL quickly enough to hit max_wal_size.</p><p>In that situation, increasing max_wal_size or adjusting checkpoint_timeout may be worth investigating.</p><p>Also pay attention to sync_time. If syncing takes a large portion of total checkpoint time, your storage latency is showing up directly in Postgres. It is also useful to compare this against buffers_backend from the background writer statistics because if the checkpoint and background writer aren&#39;t keeping up, the query-serving backends can end up doing the writes themselves and stall queries.</p><h3>pg_stat_wal</h3><p>If pg_stat_checkpointer tells you about checkpoints, pg_stat_wal tells you about WAL generation itself.</p><p>wal_records is the total number of WAL records generated, while wal_fpi counts full-page images written to WAL. A full-page image is a complete copy of a page rather than just the individual change, and it is used on the first modification to a page after each checkpoint to protect against torn pages during a crash.</p><p>Then there is wal_bytes, which is probably the most straightforward metric: the total WAL volume generated.</p><p>wal_buffers_full tells you how many times a backend had to flush WAL early because the in-memory wal_buffers was full. And wal_write and wal_sync count WAL write and fsync calls.</p><h3>What Does Healthy WAL Look Like?</h3><p>wal_buffers_full should generally be low or zero. If it keeps climbing, your WAL generation rate may be too high for the current wal_buffers size, forcing backends to flush WAL early instead of batching it efficiently. Increasing wal_buffers can help in that situation.</p><p>A persistently high full-page-image ratio can also be a clue that checkpoints are happening too frequently. Remember that after each checkpoint, the first modification to a page can require another full-page image, so checkpoint frequency directly affects WAL volume.</p><p>And if wal_write_time or wal_sync_time is increasing, your WAL storage may be becoming a bottleneck. WAL is directly involved in commit durability, so slow WAL syncing can directly increase transaction commit latency.</p><p>This gives us a useful chain to remember:</p><p><strong>checkpoint frequency → WAL full-page-image volume → WAL disk I/O → commit latency</strong></p><p>So if commits suddenly feel slow, don’t just look at the queries themselves. Check pg_stat_wal for sync time and FPI behaviour, then check pg_stat_checkpointer to see whether checkpoints are happening too frequently, and finally look at pg_stat_bgwriter and pg_stat_io to understand whether your buffers and storage are keeping up.</p><h3>Why Archive WAL At All?</h3><p>There are two major reasons to archive WAL.</p><p>The first is <strong>Point-in-Time Recovery</strong>, or PITR. If your last base backup was taken at midnight and something went wrong at 3 PM, you don’t want to lose everything between midnight and 3 PM. With archived WAL, you can restore the base backup and replay WAL until just before the disaster.</p><p>The second reason is standby bootstrapping. If a standby falls too far behind for streaming replication to catch up, it can fetch older WAL segments from the archive.</p><p>Without WAL archiving, once a WAL segment is recycled, that history is gone. You can restore to your last full backup, but you can’t restore to some arbitrary point between that backup and the disaster.</p><h3>Should WAL Archiving Be Enabled?</h3><p>By default, archive_mode is off.</p><p>For a production database that actually matters, you generally want WAL archiving enabled using archive_mode = on or, where appropriate, always, together with a working archive_command.</p><p>And yes, object storage such as S3 is a very common place to put those archived WAL segments. archive_command is simply the shell command Postgres executes for each segment. You could technically make that command upload directly to S3, but in practice, a proper backup tool is usually the better option.</p><h3>Do I Need A Backup Tool?</h3><p>I would strongly recommend using a real backup tool such as <strong>pgBackRest</strong> or <strong>WAL-G</strong> instead of trying to build the entire process yourself with a custom archive_command.</p><p>Restoring a Postgres database is genuinely complicated. You need the correct base backup, the correct chain of WAL segments, and the correct recovery target. Trying to piece all of that together manually in the middle of an outage is not something you want to discover you’re bad at.</p><p>Tools like pgBackRest and WAL-G handle things such as compression, parallel upload and download, retention policies, backup verification, and management of the base backups and archive_command / restore_command.</p><h3>When Does A WAL Segment Actually Get Recycled?</h3><p>Roughly speaking, a WAL segment can be recycled once all of the things that might still need it are done.</p><p>It needs to be old enough that crash recovery no longer requires it because the relevant checkpoint has completed. If archiving is enabled, it also needs to have been successfully archived. And it can’t still be required by wal_keep_size or an active replication slot.</p><p>This leads us to one of the classic Postgres incidents.</p><h3>Classic Incident — WAL Fills The Disk</h3><p>Imagine you have WAL archiving enabled, but the archive command is broken.</p><p>Maybe the destination is unreachable.</p><p>Maybe permissions changed.</p><p>Maybe the archive storage is full.</p><p>Whatever the reason, Postgres cannot confirm that the WAL segments were successfully archived. That means those segments cannot safely be recycled, so they start piling up on disk.</p><p>Eventually, the database disk can fill completely.</p><p>This is a surprisingly common root cause of “why did my Postgres disk suddenly fill up?” incidents.</p><h3>pg_stat_archiver</h3><p>If archive_mode is enabled, pg_stat_archiver gives you the monitoring information for WAL archiving.</p><p>archived_count, last_archived_wal, and last_archived_time tell you about successful archiving.</p><p>Then you have failed_count, last_failed_wal, and last_failed_time for failures.</p><p>If failed_count keeps climbing, your archive command is broken. The exact cause could be something like a full disk, incorrect permissions, or an unreachable storage target.</p><h3>Breathe In…</h3><p>That might have been a long post already, so I will wrap it up here for the first part. We will cover the statistics numbers that explain the larger context (database level, table level, etc,. ) in the next part.<br>Until then, さようなら.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d0a974981c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But What are Triggers and Views in Postgres? (in-depth)]]></title>
            <link>https://medium.com/@shekdivyanshu/but-what-are-triggers-and-views-in-postgres-in-depth-214c3e36f8b4?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/214c3e36f8b4</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 16:50:17 GMT</pubDate>
            <atom:updated>2026-07-20T16:50:39.440Z</atom:updated>
            <content:encoded><![CDATA[<p>A few questions would be enough to trigger your curiosity : Can you run your own custom logic whenever a query is executed, overwriting PostgreSQL’s defaults? Can you hide some columns of your table from some people ? Can you cache a query’s result ? We will look at the answers to these questions throughout our blog.</p><h4>Before We Begin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-YA8P-3rP-WF5_-FCPAMA.png" /></figure><p>This is a simplified view of how the database converts query into results. For this blog, we focus on only two parts: the Query Tree and the Rule System. The query tree is a tree data structure and there are few major components to it :</p><ul><li>statement — the statement like SELECT or INSERT</li><li>range table — the tables which must be queried to produce result. Internally PostgreSQL uses numbers instead of table names</li><li>result relations — points to tables which need to be modified (not the case for SELECT queries)</li><li>target list — what data are we working with. For SELECT it would be the columns we want back from a query.</li><li>qualification — which rows qualify for results, this is determined by the WHERE clause</li><li>join tree — represents the FROM clause and JOINs (if any)</li></ul><p>The main statement is the root of tree. Then the components discussed above form the branches of the tree. Once the query tree is constructed, the rule system can take control. The rule systems are query-level logic. We will look at rules in more detail ahead. But in short they can be used to run custom pieces of SQL commands or run side-effects, whenever a statement like INSERT, DELETE or UPDATE is run against a table or a view.</p><h3>Views</h3><p>A view as the name suggests, is a “view-only” (mostly!) entity in the database. A view is a virtual table, it only “reflects” the data of underlying table(or tables). A view isn’t stored on disk, it is just a stored query which re-runs when we ask for data from the view.</p><pre>-- imagine users table with columns : name, age, phone, address, height, weight<br><br>CREATE VIEW users_contact_view AS <br>  SELECT name, phone, address FROM users<br><br>-- query the view<br>SELECT * FROM users_contact_view <br><br>-- try doing a write operation<br>INSERT INTO user_contacts_view (name, phone, address) VALUES (&#39;Sung Jinwoo&#39;, 99999, &#39;Korea&#39;)<br>-- in most cases the above query will fail<br>-- views are mostly read-only!!</pre><p>Now this view only returns us user’s name, phone and address and not their weight or height. Well how does it work if a view stores no data ?</p><ol><li>Parser turns the query <em>SELECT * FROM users_contact_view </em>into a query tree (with the components we discussed above)</li><li>The rule system notices it is a view (not an actual table), it rewrites the query, such that it now fetches data from the underlying “real” tables. If the view is based upon another view (nested views), the rule system will recursively rewrite the query so that all the range tables are actual tables.</li><li>The updated query is passed to planner. The rewritten query received is messy, planner will try to optimise the execution by flattening all the subqueries.</li></ol><pre>-- query the view<br>SELECT * FROM users_contact_view<br><br>-- tranformed query by rule system<br>SELECT * FROM<br>  (SELECT name, phone, address FROM users)<br>users_contact_view -- this is an alias name, same as view&#39;s name<br></pre><h4>Updatable Views</h4><p>I said earlier :</p><blockquote>A view as the name suggests, is a “view-only” (mostly!) entity in the database.</blockquote><p>We will now see when is the “mostly” case violated. An updatable view is a special view which can accept writes, updates or deletes from an user and apply changes to the underlying tables. To qualify as an updatable view, a view must :</p><ul><li>Pull from <strong>exactly one table</strong> (or another updatable view) in its FROM clause</li><li>Have <strong>no</strong> DISTINCT, GROUP BY, HAVING, LIMIT, or OFFSET</li><li>Have <strong>no</strong> UNION, INTERSECT, or EXCEPT</li><li>Have <strong>no</strong> aggregate functions (SUM, COUNT, etc.), window functions, or set-returning functions</li><li><strong>not </strong>break any integrity constraint of the underlying table</li></ul><p>Even in an updatable view, individual columns can be read-only. A column is writable only if it’s a direct, plain reference to a real table column. Computed columns are always read-only.</p><h4>Advanced Options</h4><pre>-- create an updatable view<br>CREATE VIEW tall_ppl_view AS <br>  SELECT * FROM users WHERE height &gt; 175<br><br>-- create a view on top of the previous view<br>CREATE VIEW bulky_tall_ppl_view AS<br>  SELECT * FROM tall_ppl_view WHERE weight &gt; 80<br><br>-- now insert into users through tall_ppl_view<br>INSERT INTO tall_ppl_view (name, age, phone, address, height, weight) VALUES<br>  (&#39;John&#39;, 40, 66666, &#39;Japan&#39;, 169, 90)<br>-- it succeeds, but wait! height = 169 &lt; 175</pre><p>Even though we created the view with the promise that height must be greater than 175 cms, we violate our promise when we insert a row with height 169 cms. This can cause problems in some cases as we just inserted a row we can’t see.</p><p>Adding WITH CHECK OPTION makes PostgreSQL refuse any write that would produce a row invisible through the view.</p><pre>-- create an updatable view<br>CREATE VIEW tall_ppl_view AS <br>  SELECT * FROM users WHERE height &gt; 175<br>  WITH CHECK OPTION <br><br>-- now insert into users through tall_ppl_view<br>INSERT INTO tall_ppl_view (name, age, phone, address, height, weight) VALUES<br>  (&#39;John&#39;, 40, 66666, &#39;Japan&#39;, 169, 90)<br>-- this would fail. Good!</pre><p>Imagine another case :</p><pre>-- create an updatable view<br>CREATE VIEW tall_ppl_view AS <br>  SELECT * FROM users WHERE height &gt; 175<br> <br>-- create a view on top of the previous view<br>CREATE VIEW bulky_tall_ppl_view AS<br>  SELECT * FROM tall_ppl_view WHERE weight &gt; 80<br>  WITH LOCAL CHECK OPTION<br><br>-- insert through bulky_tall_ppl_view<br>INSERT INTO bulky_tall_ppl_view (name, age, phone, address, height, weight) VALUES<br>  (&#39;Elf&#39;, 100, NULL, &#39;Forest X&#39;, 40, 100)<br>-- this would succeed</pre><p>Note that Elf would still be inserted into users as the check option was verified “locally”, and because weight of the elf is greater than 80 kgs which was the criteria for visibility in bulky_tall_ppl_view. But because it does not satisfy the visibility rule for tall_ppl_view on which the new view is based upon, we might want the elf row to be discarded in some cases. You can either add another check option on tall_ppl_view, but it would get messy if we have many nested views — adding a check option on all views.</p><p>The cleaner way to do that would be :</p><pre>CREATE VIEW bulky_tall_ppl_view AS<br>  SELECT * FROM tall_ppl_view WHERE weight &gt; 80<br>  WITH CASCADED CHECK OPTION<br><br>-- insert through bulky_tall_ppl_view<br>INSERT INTO bulky_tall_ppl_view (name, age, phone, address, height, weight) VALUES<br>  (&#39;Elf&#39;, 100, NULL, &#39;Forest X&#39;, 40, 100)<br>-- this would fail :)</pre><p>Well that was a lot about views I guess. Let’s move on to the next section. To read more you can read the official documentation : 🔗<a href="https://www.postgresql.org/docs/current/sql-createview.html"><em>Create Views</em></a><em> </em>and 🔗<a href="https://www.postgresql.org/docs/18/rules-views.html"><em>Rules-Views</em></a>.</p><h3>Triggers</h3><p>A trigger is a piece of code that runs on occurence of an event in the database system. Now, there are a few aspects to triggers:</p><ul><li>a piece of code — Procedural Languages</li><li>an event — INSERT, UPDATE, DELETE, login, etc</li><li>the system — rows, tables or entire the database server</li><li>the timing — when does a trigger run (before or after event occurs)</li></ul><p>We will cover only triggers attached to rows, tables and views (DML) and not database wide triggers such as on logging in or altering a table (DDL level events) which are also known as event triggers.</p><p>For regular triggers, the triggering actions can be INSERT, DELETE, UPDATE, MERGE and TRUNCATE. Once decided what statement a trigger will respond to, the next question is when should the trigger run — just before the statement starts executing or after it has finished. For views, we have one more option that is INSTEAD OF.</p><p>Before we explain how these all fit together, let us look at a basic PL/pgSQL functions&#39; structure. PL/pgSQL is a built in procedural language for postgres. What is a procedural language ? PostgreSQL allows user-defined functions to be written in other languages besides SQL and C. These other languages are generically called <em>procedural languages</em> (PLs).</p><pre>-- a function structure in PL/pgSQL<br>CREATE OR REPLACE FUNCTION function_name(input_param text)<br>RETURNS text AS $$<br>DECLARE<br>    -- define variables you&#39;ll use later<br>    my_variable integer := 10;<br>BEGIN<br>    -- Do calculations, updates, or selects here<br>    RETURN &#39;Hello &#39; || input_param;<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>A <em>trigger</em> is a special type of user defined function which runs automatically based on an event. A <em>trigger function</em> is just a regular function with RETURNS TRIGGER. On its own it does nothing — you have to attach it to a table via CREATE TRIGGER before it ever runs. Let’s look at a trigger function that insert a message into an alerts table whenever an expensive item is added:</p><pre>CREATE FUNCTION log_changes()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    -- &#39;NEW&#39; refers to the row you just typed in<br>    -- &#39;OLD&#39; refers to the row before it was changed<br>    IF NEW.price &gt; 100 THEN<br>        INSERT INTO alerts(msg) VALUES (&#39;Expensive item added!&#39;);<br>    END IF;<br>    <br>    RETURN NEW; -- Tell the database to proceed with the change<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>Once the trigger function is setup, the next step is to wire it to a trigger. This would actually run the above trigger function.</p><pre>CREATE TRIGGER expensive_item_trigger -- name your trigger<br>AFTER INSERT ON cart_table -- which table should this trigger be called for <br>FOR EACH ROW -- should run for all cart items, hence for each row<br>EXECUTE FUNCTION log_changes(); -- attach the function we created above</pre><p>Here is the simplified general syntax for creating a trigger:</p><pre>create trigger trigger_name<br>{ before | after | instead of } { insert | update | delete | truncate }<br>on table_name<br>[ for each { row | statement } ]<br>[ when (condition) ]<br>execute function function_name();</pre><p>Don’t worry if you don’t get what the above code does. We will go step-by-step. The RETURN in the function body is responsible for telling what to do with a current row. It’s similar to what a return keyword does in any programming language — return a result that will be used by the caller.</p><h4>Statement Level Triggers</h4><p>These are triggers attached to a table/statements. Statement-level triggers fire once for the whole SQL command, not per row. So if your INSERT command touches 1000 rows, the statement trigger would be called just once after the operation on these 1000 rows is over. Since they’re not handling a specific row, there’s nothing meaningful to return. So you always just return NULL, a statement level trigger function would look like:</p><pre>CREATE FUNCTION my_statement_trigger_func()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    -- do something (log, notify, etc.)<br>    RETURN NULL;   -- always for statement-level<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>FOR EACH STATEMENT is what makes this statement-level — fires once total, no NEW/OLD available.</p><pre>CREATE TRIGGER my_statement_trigger -- trigger name<br>AFTER INSERT ON my_table -- attach to a tabl <br>FOR EACH STATEMENT -- declare it&#39;s a statement level trigger<br>EXECUTE FUNCTION my_statement_trigger_func(); -- attach the function</pre><h4>Row-Level BEFORE Triggers</h4><p>Note that NEW means the row after it would be updated, OLD is the current row. We can just return NEW to denote that we have made no changes to the user requested query. It would be applied as is.</p><pre>BEGIN<br>    RETURN NEW;   -- go ahead, write the row unchanged<br>END;</pre><p>You can alter the row inside the trigger before returning it. PostgreSQL will write your modified version instead of the original. So imagine attaching a timestamp to each row before the item is added to the db:</p><pre>CREATE FUNCTION set_timestamp()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    NEW.updated_at = now();    -- add a timestamp<br>    NEW.name = upper(NEW.name); -- force name to uppercase<br>    RETURN NEW;   -- PostgreSQL writes THIS modified version<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>And attach this to a trigger via :</p><pre>CREATE TRIGGER set_timestamp_trg -- name the trigger<br>BEFORE INSERT OR UPDATE  -- declare its a before statement<br>ON users_table -- name the table on which trigger is called<br>FOR EACH ROW -- since its a row evel trigger<br>EXECUTE FUNCTION set_timestamp(); -- attach the timestamp function</pre><p>Returning NULL tells PostgreSQL to skip that row, don&#39;t write it at all.</p><pre>BEGIN<br>    IF NEW.salary &gt; 1000000 THEN<br>        RETURN NULL;   -- silently block this insert<br>    END IF;<br>    RETURN NEW;<br>END;</pre><h4>Row-Level AFTER Triggers</h4><p>AFTER triggers fire after the row is already written to the table. The deed is done — there’s nothing left to change. So whatever you return doesn’t matter. Convention is to return NULL, but it&#39;s irrelevant. Use AFTER triggers for side effects — logging, updating other tables, sending notifications — not for modifying the row itself.</p><p>So for the example we create a function that would add a log to a logs table everytime a row is deleted from users table.</p><pre>CREATE FUNCTION log_delete()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    INSERT INTO audit_log VALUES (OLD.id, now(), &#39;deleted&#39;);<br>    RETURN NULL;   -- ignored, row&#39;s already gone<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>And again attach the function to a trigger now:</p><pre>CREATE TRIGGER log_delete_trg -- name the trigger<br>AFTER DELETE -- declare its a after trigger that runs on delete command<br>ON users_table -- name the table on which it triggers<br>FOR EACH ROW -- a row level trigger<br>EXECUTE FUNCTION log_delete(); -- attach the function we created</pre><h4>INSTEAD OF Triggers</h4><p>As we discussed earlier, this trigger works only for Views. As views have no real storage, we must define what happens to the underlying tables when a trigger is instantiated. They work similar to the row level BEFORE trigger.</p><p>For the sake of example we have two tables —authors and books. Let’s first create a view named book_details_view as :</p><pre>-- creates a view<br>CREATE VIEW book_details_view AS<br>SELECT b.id, b.title, a.name AS author_name, a.id AS author_id<br>FROM books b<br>JOIN authors a ON a.id = b.author_id;</pre><p>Now let’s write a trigger that will delete the underlying book from the books table whenever a delete is called on the book_details_view. And probably no more need to tell you, the next step is writing a trigger function:</p><pre>CREATE FUNCTION book_details_delete()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    DELETE FROM books WHERE id = OLD.id; -- delete from underlying books table<br>    RETURN OLD; -- returns the deleted row<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>And unsurpsingly the last step is to wire this function to a trigger :</p><pre>CREATE TRIGGER book_details_delete_trg<br>INSTEAD OF DELETE -- declare that its a INSTEAD OF, triggered on Deltes<br>ON book_details_view -- attach to the view<br>FOR EACH ROW<br>EXECUTE FUNCTION book_details_delete(); -- call the above function</pre><h3>Conclusion</h3><p>So that might have been really dense, but you made it. To recap, we saw what are Views. We looked at the parse tree structure too, which is passed to the tree structure. Once parsed, the SQL queries are run according to the Rule System rules. The rules also contain provision to run custom pieces of SQL queries — FUNCTIONS and TRIGGERS. We studied about the various ways a trigger can be called.</p><p>That’s it for this part. See you soon, on the other side of knowledge :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214c3e36f8b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PgBouncer, PGKeeper … and the little Catfish]]></title>
            <link>https://medium.com/@shekdivyanshu/the-little-catfish-2618d395cbd2?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2618d395cbd2</guid>
            <category><![CDATA[pgbouncer]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Fri, 29 May 2026 14:16:47 GMT</pubDate>
            <atom:updated>2026-05-29T14:16:47.613Z</atom:updated>
            <content:encoded><![CDATA[<p>So a few weeks ago I came across a fresh new article on my tech feed : “PGKeeper : Building the Bouncer We Needed For Postgres”. Half sure I would understand it, I still read it halfway, fed the other half to Claude, read the various libraries and algorithms mentioned and a lot of thinking. It took me a week to grasp the blog, but it was fun. Before I finished the blog, I was certain it would be a fun little side project. So another two weeks passed by and I finished what might be the second most complex project of my life.</p><p>That said the blog assumes you have prior experience with connection pooling with PgBouncer. If not, here is a good one for you :<a href="https://planetscale.com/blog/scaling-postgres-connections-with-pgbouncer">PlanetScale Guide to PgBouncer</a>.</p><h4>The Problem with PgBouncer</h4><p>Honestly its great. Almost everyone uses it — until you come across few unique problems :</p><ul><li>It treats all queries equally. Serving users should be the prime focus of any user oriented application, but assume all your connections being occupied by analytic jobs and the users keep waiting. There is no way in PgBouncer to let users have a higher weight in connection assignment.</li><li>Its single threaded, one thread runs all the connection assignment job. It’s fine with a smaller number of requests, but with large number of requests demanding a connection, it’s a significant bottleneck. Puts a cap to vertical scaling .</li><li>It lacks load management. When queries can’t be served instantly they are queued. Imagine a request waiting for a couple of second, the frustrated user might have cancelled it already. But there it is, still occupying a seat in the queue. And it is not alone, there could be so many other cancelled, ditched requests lying. Further, it starts a waterfall effect, new queries end up behind these dead requests. PgBouncer reads through all the queries, finds it was cancelled, removes them and then reach our ‘new’ request. By that time, even the new query gets stale.</li><li>Lastly, Figma needed more with their pooler. Namely, flags and observability. These are important metrics reflecting the health of pooler and helps the application to warm up before an issue occurs.</li></ul><h4>PGKeeper</h4><p>This is where PGKeeper came in. Engineers at Figma took a year to develop an in-house connection pooler, that is more than a connection pooler. Its a private tool, that can handle request surges, manage load intelligently, differentiate between a high and low priority request, is multi-threaded and provides useful insights and metrics about health of the service.</p><p>Obviously, I didn’t implement everything, but it is still a lot. I will only cover the parts I implemented. If you are interested you can read the <a href="https://www.figma.com/blog/pgkeeper-building-the-bouncer-we-needed-for-postgres/">original PGKeeper blog</a> too.</p><h3>Catfish</h3><p>First of all, what’s up with the name? Well I think connection poolers are kind of like catfish accounts. They give a lavish view of what is mostly a simpler, not-so-grand thing. Connection poolers make your app believe there are a lot of connection open and free to acquire connections. The reality is different — Postgres connections are expensive and we can’t have many of them. We can’t keep closing old ones and reopen new ones in their place, we waste a lot of server resources that way. So we never (we do, just after a long time) close them, we keep recycling them. A smaller number of connections are to be used by a large number of applications.</p><p>Catfish is written on top of jackc/pgx library in Golang, arguably the best library to work with Postgres. I will walkthrough the implementation step by step in this blog, trying to keep it simple and intuitive. The first part I implemented was the connection pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSKPsZTJRq7K7KlNC8nlQQ.png" /><figcaption>An overview of Catfish</figcaption></figure><h4>Enter The Pool</h4><p>This was relatively an easier part. It just wraps around the core pgxpool package with minor tweaks here and there. The library is based on an assumption that each (user, database) pair gets a separate pool. However I made another decision to keep a global settings for all the pools — MinConns, MaxConns, MaxConnIdleTime, etc,. These are set once in the config file. All pools inherit this global setting.</p><p>Take a look at the Exec() function from catfish, it wraps around pgxpool’s execute function. A connection is withdrawn from Catfish’s pool and is passed to pgxpool’s Exec().</p><pre>func (p *Pool) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {<br> // acquire a connection from pool<br> conn, err := p.inner.Acquire(ctx)<br> if err != nil {<br>  return pgconn.CommandTag{}, fmt.Errorf(&quot;%w: %w&quot;, ErrAcquireConn, err)<br> }<br> defer conn.Release()<br><br> // get response back from pg and return back the same response to user<br> cmdTag, err := conn.Exec(ctx, sql, args...)<br> if err != nil {<br>  return pgconn.CommandTag{}, fmt.Errorf(&quot;%w: %w&quot;, ErrExecConn, err)<br> }<br> return cmdTag, nil<br>}</pre><p>The interesting parts are rollbackIfNeeded and drainRows. Remember what we said about recycling connections, we don’t close connections once the user has received the response for his query. The same connection will be used for running other queries from users of the same pool. But what if the previous query ended up in an unfinished transaction (neither committed nor rolled-back) or the user didn’t read the results? Those results are still pending to be read inside the connection. If we just pass around the connection to another user, he will read these weird results before he reads his own response.</p><p>We use pgx.Conn.AfterRelease() function. This function is run automatically after a connection is released but before it is returns to the pool — the perfect time to run side effects. We simply check if the last query resulted in an unfinished transaction, in which case we ROLLBACK the transaction via rollbackIfNeeded(). Similarly if the user had left unread rows on the connection we “drain” them. Which means we simply read them using drainRows()</p><p>There are a few more details to handle here : auto-closing the connections after user finished reading her response and auto warming the pool until MinConns number of connections have been acquired. These are however better explained in the codebase itself, covering them here would make the blog kinda boring. Another design decision was not to expose any Pool.Acquire() method to users that gives them access to individual connections from a pool. This was because once acquired, user can directly run SQL queries. Instead we want the queries to pass through our proxy service which decides (based on current load) whether the query should run or be queued.</p><h4>A Simple Deque</h4><p>The next part was to implement a simple deque — a queue data structure that can accept and removes data items from both ends. There were some popular deque implementations on GitHub but for this use case they all were overkill. The reason being that we don’t have to care about resizing a queue once its full, no manual memory management. We are making a queue responsible for load management. It doesn’t have to increase its capacity for load, rather return a “we are too busy, try again later” message once the queue is full. No more requests shall be accepted beyond the queue size (configured by the user).</p><p>So the best option was to implement it myself, and it was just like another algorithmic challenge (yes, those LeetCode ones !)</p><h4>Managing Traffic with Backpressure</h4><p>This one is tricky — bunch of structs, algorithms and calculations happening all at once. The best way to understand it is an analogy :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-qg6N_K2QqbcbOGDz2t4Q.jpeg" /><figcaption>This image is the only AI generated content in the blog :)</figcaption></figure><p>Imagine a really busy restaurant, and the owner is sort of biased to the rich (I know it’s terrible). There are a fixed number of tables which we call MaxConcurrent in our case, the maximum requests that can be served at any given point. People (the requests) who can’t get a table (token/ticket) have to wait back in lines (the queues). Once a request gets a “ticket” they get a seat. One table serves one request. Keep in mind : there are multiple queues — one queue holds people of same priority together. Two different priorities, two different queues. But all priorities compete to get the same seat.</p><p>Since there is a contention among various entities (the queue members) for a single resource (the seats or tokens), we need a lock on the table to avoid race condition. The MaxConcurrent is part of this Semaphore. A semaphore is used to control access to a common resource by multiple processes/threads, it uses and internal counter (outstanding) and two atomic operations Wait (or Acquire()) and Signal (or Release()).</p><p>It’s not just that. Next comes the idea of “<strong><em>debt</em></strong>”. Remember the biased owner ? It’s the semaphore. Whenever a request from the higher priority queue is found to wait because of the lower priority ones, the semaphore can order a debt increase on the lower priority queues. For example a debt of 2 on the lower priority queue means 2 seats are reserved for the higher ones, the prior can’t acquire them. It is reasonable because increasing debt means increasing number of reserved seats, which allows the critical requests waiting in the line to be served.</p><p>The reverse of this situation is when a critical query was served without any wait at all, it might mean the owner was overly strict with other customers. Maybe more than required seats are reserved. In this case the owner can declare a decrease in the debt. An important part of this self-adjusting debt is forgiving the debt entirely. This is by default done every 10 seconds. We can deduce given a queue size of 200, 3 queues and assuming 10ms for each request to be served, that it takes around 6 seconds until a set of completely new queries fill up the queues. A new set means a new pattern of incoming requests, we can’t use the formerly learned debt to handle it.</p><p>The final part to backpressure is : <strong><em>CoDel</em> </strong>(Controlled Delay) algorithm. It is a load shedding algorithm that sheds work based on how long requests have been waiting, not how many are queued. Imagine a customer in our imaginary restaurant that came at 7&#39;O clock, will he rather wait until midnight or decide to leave and come back tomorrow. The same happens with requests. Read the load management issue of PgBouncer we covered at the start. It is a waste to serve queries in a FIFO sense when the queue is too long. Resolving older requests first, only to discover they already expired or were cancelled. All this while the newer requests are put on hold at the back. The CoDel algorithm is used to switch from FIFO to a LIFO order of request execution and vice-versa when the load is low.</p><p>This is why we needed a deque in the first place, all priority queues are actually “priority deques” controlled by CoDel. A reap() is used to kill stale queries periodically from the queue. The reap timeout is lower during LIFO mode, which means it aggressively kills requests when queue is under a heavy load.</p><p>A final issue with CoDel is another race case condition. A context expired or user manually cancelled a request which was waiting in the queue, but at the exact moment it was admitted (given a ticket) by the semaphore. Carelessly handling this would both report to the user with “sorry we are busy” as well as actually execute it. That’s not good ! Hence we wrap the query in a coDelWaiter struct :</p><pre>type coDelWaiter[T any] struct {<br> // time of enqueue, used for reap<br> enqueued time.Time<br> // An atomic state variable (0 = waiting, 1 = admitted, 2 = client expired)<br> state uint32<br> // A channel used to signal the outcome (true = success, false = dropped)<br> c chan bool<br> // the actual data carried by the request<br> payload T<br>}</pre><p>This struct assigns a Go channel to the waiting customer. Whenever admit() (semaphore accepted it) or ctx.Cancel() (rejected for waiting too long) is called, these functions try to atomically swap the state variable from the struct. The winner of this contention is the one to decide what will happen to the query. If state was set to 1 by the admit() function, it will be admitted only, context cancellation loses the right to cancel the query.</p><pre>func (cw *coDelWaiter[T]) wait(ctx context.Context) error {<br><br> // the select is responsible for keeping the request blocked, smthing must happen (the cases) to wake it up<br> select {<br> // context timed out / cancelled<br> case &lt;-ctx.Done():<br>  // context cancel<br>  // try to update the state atomically<br>  // if state was = 0 (waiting), set to 2 (client expired) now<br>  didSwap := atomic.CompareAndSwapUint32(&amp;cw.state, 0, 2)<br>  if !didSwap {<br>   // failed to swap, state value must already have been = 1<br>   // i.e., admitted =&gt; no error<br>   return nil<br>  }<br>  // ctx cancelled succesfully, return error = context error to let user know<br>  return ctx.Err()<br><br> case v := &lt;-cw.c:<br>  if v {<br>   // v is true, request accepted by codel<br>   return nil<br>  } else {<br>   // reap rejected the request, send error<br>   return ErrRejected<br>  }<br> }<br><br>}<br><br>// admit will attempt to admit the request, returns true if admission successfull<br>func (cw *coDelWaiter[T]) admit() bool {<br> isAdmitted := atomic.CompareAndSwapUint32(&amp;cw.state, 0, 1)<br> if isAdmitted {<br>    cw.c &lt;- true<br> }<br> return isAdmitted<br>}</pre><p>Well that was a lot maybe. But that’s it with backpressure. I must credit the <a href="https://github.com/bradenaw/backpressure"><em>backpressure package</em></a> which helped me understand this otherwise complex code. We can now move the top layer of our system: the proxy layer.</p><h4>The Proxy</h4><p>It is the Catfish server’s configuration. The clients that want to connect to catfish service go through this layer. We can intercept the queries and responses here before they reach to user or postgres respectively. This allows a wide range of operations we can perform midway — tracking whether the last query finished or not, monitoring queries, etc,. At this layer we read the users from the config file (use a yaml reader), we read the password for each user from the .env file. We create pools (using our own pool package) for each of these (user, database) pair. This all done at start-up. The next logical step is to listen to users who want to connect. This is a simple forever running loop listening for TCP connection requests to our server. We spin-off a new goroutine to handle all clients independently. This is how we overcome PgBouncer’ s single threaded nature.</p><p>This is also where we do the client authentication part. The first is to check whether the user requesting access was allowed in the config file or not. This is important because we setup the pools already, we can’t accept dynamic connections. All the users who would compete for the fixed number of pools is decided at start-up. It also means we handle authentication ourselves. Postgres has a pg_hba.conffile that handles the authentication rules, methods and access control. The authentication process has a number of message exchanges between the app and the postgres server. This is where jackc/pgx/pgproto3 package comes in handy. It exposes all these messages as Go structs. And honestly there is a lot here, learning the auth flow as well as the message structs was a mess. And LLMs helped me a ton at this stage. I didn’t have to waste hours exploring the exact struct I needed at each step. The current state of the Catfish has Cleartext, MD5 and SCRAM-SHA-256 methods of authentication implemented. And writing code for these was fun actually, SHA-256 in particular ( partly because university courses on cryptography finally made some sense :) ).</p><p>Covering the auth flow or the pg_hba.conf would be too much. That deserves a blog post in itself. Please bear in mind that Catfish doesn’t handle SSL authentication currently. Once authentication for the user is successful, he can finally send requests to our server. Another function clientLoop() is responsible for all handling all messages that are fired on this pool nest. The message type *pgproto3.Query is handled with a handleQuery() function. This is where backpressure comes in. Each query has to acquire a token before it can be executed. Once the response from Postgres is streamed back to the client, the acquired token is released back to the semaphore.</p><p>There are numerous little details I have left here such as clean Shutdown (multiple paths to close a connection), handling extended queries, handling query terminations, handling queries that threw error midway, etc,. Another decision I made for now was to assign each query a weight of one. It would be quite a task to think which queries have a higher weight and which ones lower. All queries hence take up a single token. Another fun side-project would be to have a lightweight machine learning model analyse and assign a weight to each query that passes by.</p><h4>Wrapping Up</h4><p>So the final stage was deploying this as a Docker Image on DockerHub (maybe GHCR too in future). As the user you can directly pull the image, mount the yaml config at runtime and you are ready to go :)</p><p>Here is the GitHub repo : <a href="https://github.com/DivyanshuShekhar55/catfish">DivyanshuShekhar55/Catfish</a></p><p>And here is the Docker Image : <a href="https://hub.docker.com/r/skywalkerx42/catfish">https://hub.docker.com/r/skywalkerx42/catfish</a></p><p>I would love to have forks and contributions (specially SSL, monitoring and password handling for now). Thanks for the read. 読んでくれてありがとう！またね。.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2618d395cbd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned about Observability in 10 days]]></title>
            <link>https://medium.com/@shekdivyanshu/what-i-learned-about-observability-in-10-days-a370c143d2ee?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a370c143d2ee</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[clickhouse]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 04:55:12 GMT</pubDate>
            <atom:updated>2026-04-12T04:55:12.178Z</atom:updated>
            <content:encoded><![CDATA[<p>I was intrigued by stories of Facebook in early days, where the idea of logging came across multiple times in various startup school videos. I came across it with Uber’s story too where they used metrics and logs to reduce “zeroes” across the globe. What exactly do they measure ? How do they get these fascinating insights ?</p><p><strong><em>Note</em></strong> : <em>I made a basic prototype too as I learned various concepts. It uses Golang, OpenTelemetry and ClickHouse DB beside other tools. But the main goal of this article is to cover concepts and tools rather than their exact implementation. So no matter your programming background you can jump along and give it a read.</em></p><h4>M.E.L.T. and OTel</h4><p>The core of observability revolves around MELT — metrics, events, logs and traces.</p><ul><li>Metrics — they tell you how is your system (the ‘server’) is behaving. They are numbers associated with a fixed point in time. Like your CPU usage at 12:05 PM or how long are queries taking to execute (percentile values) — longer queries means higher lags on the user side. Studying an aggregation would help you answer questions like if the CPU usage constantly growing. If yes, we must get a bigger machine.</li><li>Events — any important enough occurence to be tracked. A user signed-up from Japan or a payment in China failed. An aggregate would tell you important insights: 20% payments in China failed in the last hour, must be something wrong with the payment services.</li><li>Logs — they are similar to events in some ways. Think of them as a nerdy version of events because they convey more than just events. An error occurred in the mailing service at 1:09 AM because the user entered an invalid mail address. You look at the bulk of logs and notice 18% logs related to mailing service conveying the same issue, hmm might be a DDoS attack.</li><li>Traces — or also known as distributed tracing, track requests across multiple services. All the others terms we saw are related to a single server at a single point of time. Traces track a request from start to finish. They can help you understand the bottlenecks in your application.</li></ul><p>One thing must be clear by now : everything in observability is a number or an information. A sign-up info could look like : {msg: “signup from Japan”} or {event: “signup”, country: “Japan”, time: 12:09PM}or any other random structure (may not be JSON). If you have been in the world of coding for a little long, you know we have an obsession with ‘decoupling’, in other words — <em>standardisation</em>. So enter <a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a>.</p><p>OpenTelemetry is the standard way to produce MELT data. OpenTelemetry, or OTel for short, is an open-source framework that acts as a plugin with your existing code and can produce telemetry data (<em>tele </em>means remote/distributed and <em>metry </em>means to measure). In the modern world where infrastructure is based on large number of microservices, maybe all using a different programming language, and a large number of tools (PostgreSQL, Kubernetes, Docker), producing telemetry (read MELT) data manually would be so messy. OTel simplifies this process with a set of simple APIs.</p><p><strong><em>Coding Part : Setting-Up OTel</em></strong><em>: </em>If you are interested in the coding part, read through this section, else skip to the next part. The core setup is done here: <a href="https://github.com/DivyanshuShekhar55/Shuzook/blob/main/shazam/internals/otel/otel.go"><em>https://github.com/DivyanshuShekhar55/Shuzook/blob/main/shazam/internals/otel</em></a><em> . </em>If you observe closely you would notice the use of context. This is how the requests are tracked by OTel.</p><h4>OLAP Databases &amp; Observability Backends</h4><p>Reiterating myself once more : everything in observability is a number or an information. And plain text or numbers alone wouldn’t be of much value. They only make sense when aggregated and shown in a way easier to understand for the decision makers. A single signup event wouldn’t mean much. But a bulk of these telemetry data would be convey precious knowledge: number of people who signed up last month grew by 10%, percentage of people who liked dancing cats (maybe boost cat videos on the home feed), number of people from South Asia dropped by 6% (which calls for a new marketing strategy).</p><p>This is a two step process:</p><ul><li><strong>Storage of telemetry data</strong>: this is the world of <strong>OLAP databases</strong> — databases optimised for analytical queries over petabytes of data. The most common optimisation being columnar storage of data. Major providers of data storage are Amazon Redshift, Snowflake (both are data warehouse providers) and ClickHouse. I chose ClickHouse, a modern analytical database. Though I haven’t yet dived into it much, I had a little prior experience with columnar storage (Cassandra).</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fa7rmLeGK1v8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Da7rmLeGK1v8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fa7rmLeGK1v8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6f5c7c746a6174816fa7fb3870e53f/href">https://medium.com/media/5d6f5c7c746a6174816fa7fb3870e53f/href</a></iframe><ul><li>The second part is an <strong>observability platform</strong>. This is where telemetry data ‘makes sense’. Graphs, charts, hierarchical representation, searching across logs and many more features that comes handy during debugging or finding patterns in data. We either have individual tools handling different aspects of telemetry data or an all-in-one solution to observation. Prometheus (for metrics), ELK stack (for logs), Jaeger and Zipkin (for traces) are major providers focused on a single aspect of observability whereas ClickStack, New Relic, Datadog and Better Stack provide unified solution to observability.</li></ul><p>I decided to use ClickStack just because it is fairly easy to setup for dev environments and ClickStack has been rising in popularity even among the big tech companies. I could have chosen Elastic (earlier Elasticsearch) having worked with it for some time. But I needed something new !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJihGgre1BLo8_SGOEUmkg.png" /><figcaption>A broad view of ClickStack</figcaption></figure><p>ClickHouse serves as the analytical database and HyperDX is the UI where you can monitor your application’s health. There are various ways the stack can be hosted, but they primarily fall under two categories — managed and self-hosted. Managed ClickStack provides a cloud native storage and access to your telemetry data. Open source stack is managed by you, the application developer. There are various alternatives even in the self hosted path, I chose what the docs call all-in-one Docker container. A single container that gives you storage plus the Hyper frontend.</p><p><em>Note </em>: Read more about options for deploying here : <a href="https://clickhouse.com/docs/use-cases/observability/clickstack/deployment">https://clickhouse.com/docs/use-cases/observability/clickstack/deployment</a></p><h3>Tracing</h3><p>All requests on the web carry a context with them. And when one service calls another, we can just pass this context in the metadata/header. This is the core idea behind tracking requests across different microservices. Actions with same metadata represent the same trace. A single trace can have multiple spans. A span represents a sub-process in the event. For example tracing a signup request (a trace) might have multiple spans (or units of work) such as :</p><ul><li>request from signup service to DB to check if username exists</li><li>request from service to DB to insert the new user details</li><li>showing a success/failure response to user</li></ul><p>We can track all these spans individually. These are best represented as bars on a tracing backend such as Jaeger or in our case ClickStack’s Hyper DX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GnZI5VUJJFNx6ba2.png" /><figcaption>Source : Jaeger’s official docs</figcaption></figure><p>Reading traces can help you understand if a query took too long to respond (big bars) and what exactly causes the delay (large spans within a parent span). OTel creates spans on its own, but many times we need to create them manually only because we can gather more detail about requests. Read more about OTel tracing here :</p><ul><li><a href="https://opentelemetry.io/docs/concepts/signals/traces/">https://opentelemetry.io/docs/concepts/signals/traces/</a></li><li><a href="https://opentelemetry.io/docs/specs/otel/trace/api/">https://opentelemetry.io/docs/specs/otel/trace/api/</a></li><li>My code for tracing is here: <a href="https://github.com/DivyanshuShekhar55/Shuzook/blob/main/shazam/cmd/api/tracerWorking.go"><em>https://github.com/DivyanshuShekhar55/Shuzook/blob/main/shazam/cmd/api/tracerWorking.go</em></a></li></ul><h3>Logging</h3><p>Ok implementing logging is going to be a bit trickier than traces. We will start with a logging library, in our case Zap (an open source library for logging by Uber). For simple weekend projects the built in logging functions (log.Print() in Go or logging module in Python) works fine, but when our app starts to produce thousands of logs per second, we need better options — Zap for Go or structlog for Python. What exactly makes these better ?</p><ul><li>Firstly we need levels in logs. These help us differentiate severe errors (could not connect to database) from informative logs (cache miss in DB).</li><li>Performance — standard libraries will use a considerable amount of server’s memory (for tasks like assigning spaces in memory, dynamic data types). When traffic is high we can’t afford it, Zap was designed to be zero-allocation, it barely hits app’s performance.</li><li>adding contexts to logs (we can directly plug-in OTel to Zap)</li></ul><p>Next, we need to consider an important point : analytic databases are often optimised for bulk inserts. Sending logs one at a time will work but this approach is not recommended. We need a way to bunch a group of logs and then send a bulk insert request to ClickHouse. One way to do it is to put all incoming logs inside a file (called a <strong>log-file</strong>) and once ‘enough’ logs are collected in the file, send all the logs together.</p><p>How we decide on the ‘enough’ part? This is either via a time-scheduled cron job (keep collecting logs in the file for 10 seconds then send them all), or file size based cron job (if the file hits for example 2KB size send all the logs). Once we dump all the logs to database, we usually archive them for sometime (7 days, a month or whatever). A new file is created and the new logs start going inside this log file. We call this log rotation. I implemented log rotation via lumberjack library in Go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbLuRv4zjTyOf2dGCislfA.png" /><figcaption>Implementing Logging</figcaption></figure><p>You might have noticed we have not covered one part yet — <strong>FluentBit</strong> (honestly this has a comparatively greater learning curve and I have just grazed the surface here). It acts as the log shipper, it collects data from any source, processes it in a pipeline, and ships it anywhere. FluentBit has 100+ plugins for accepting logs supports metrics and traces too (but I didn’t use them). We can write custom parsers (converting raw logs), filters (different data tags, different processing), route data (send ‘info’ tagged logs to S3, errors to clickhouse) and modify data too. It also got an in-built retry logic to resend data in case it fails to be inserted into DB.</p><p>FluentBit has a sibling <strong>Fluentd</strong>, a buffed up version of FluentBit. A common pattern is to have a fluent bit attached to each node (instances/servers) to ship logs and forward them to Fluentd (or OTel collector works too), which aggregates them and ships to the destination data store. For my implementation, this was an overkill and I didn’t use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_DX7oZ5uFfIsAoaA.png" /><figcaption>Source : <a href="https://fluentbit.io/blog/2020/12/03/common-architecture-patterns-with-fluentd-and-fluent-bit/">https://fluentbit.io/blog/2020/12/03/common-architecture-patterns-with-fluentd-and-fluent-bit/</a></figcaption></figure><ul><li>Read more on Zap here: <a href="https://betterstack.com/community/guides/logging/go/zap/">https://betterstack.com/community/guides/logging/go/zap/</a></li><li>My implementation of logging : <a href="https://github.com/DivyanshuShekhar55/Shuzook/blob/main/shazam/cmd/api/loggerWorking.go">Logger🔗</a> and <a href="https://github.com/DivyanshuShekhar55/Shuzook/tree/main/shazam/fluent-bit">fluent-bit setup🔗</a></li></ul><h3>Metrics</h3><p>The final section in observability. They are relatively simple, OTel provides us instruments that can be used to calculate important metrics. The major instruments are :</p><ul><li>counters — strictly increasing numbers, which can be increased programmatically with an Add() function. For example increment the counter value by one whenever a request comes (track number of requests per hour or per day)</li><li>up-down counters — can be incremented or decremented (use Add(-1) to decrement). Useful for numbers like number of active users on a website (add one when a new user shows up, subtract one when a user leaves) or number of active database connections (monitoring connections is essential to quality database pooling).</li><li>histograms — essential for percentile calculations. What are percentile values? (P.S. they are probably the most famous concept in observability) A percentile value pX would tell you how long do X% of queries take to finish. For example if your p90 value is 150ms it would mean 90% requests coming from users are finished within 150ms. They help in understanding how long users on the slower side of network will have to wait before a result shows up.</li><li>Read all the instruments here : <a href="https://opentelemetry.io/docs/specs/otel/metrics/api/">https://opentelemetry.io/docs/specs/otel/metrics/api/</a></li></ul><p>OTel can be setup to collect and send these numbers after a fixed time interval. Look at the following code for setting up a meter collector (it collects metric values every 3 seconds):</p><pre>func newMeterProvider() (*metric.MeterProvider, error) {<br> metricExporter, err := stdoutmetric.New(stdoutmetric.WithPrettyPrint())<br> if err != nil {<br>  return nil, err<br> }<br><br> meterProvider := metric.NewMeterProvider(<br>  metric.WithReader(metric.NewPeriodicReader(metricExporter,<br>   // Default is 1m. Set to 3s for demonstrative purposes.<br>   metric.WithInterval(3*time.Second))),<br> )<br> return meterProvider, nil<br>}</pre><h3>Conclusion</h3><p>Honestly, it was challenging to learn but it was fun too. I hope you loved reading my blog. Please drop a clap and give a star to my GitHub repo : <a href="https://github.com/DivyanshuShekhar55/Shuzook">https://github.com/DivyanshuShekhar55/Shuzook</a>.</p><p>See you next time, on the other side of knowledge :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a370c143d2ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But what is Data Integration Problem? CDCs, Batching, ETLs & FDWs]]></title>
            <link>https://medium.com/@shekdivyanshu/but-what-is-data-integration-problem-cdcs-batching-etls-fdws-97cb5a0dffd6?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/97cb5a0dffd6</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 05:35:51 GMT</pubDate>
            <atom:updated>2026-03-06T05:35:51.615Z</atom:updated>
            <content:encoded><![CDATA[<p>The requirement seems simple: you have a database server and you need to move a subset of its data to another server. In practice, the task is complex — there can be failures on individual rows, data duplication, retry logic, performance bottlenecks, and costs to consider.</p><p>We cover some common ways to handle this. Though the blog focuses primarily on PostgreSQL, the same concepts can be extended to a broader range of databases.</p><h3><strong>Batching</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lf0t01QyO4uy9i-jUDVIcA.png" /></figure><p>Think of your data as an array. Batching is like a sliding window over that array — you send data in smaller chunks rather than all at once. There are a few common ways to partition data.</p><p>The first approach is <strong>offset-based batching</strong>. While straightforward, it can become problematic as data grows: PostgreSQL still reads all preceding rows regardless of which batch you are processing. Worse, if a new row is inserted between Batch 1 and Batch 2, your “page” shifts, causing you to duplicate or skip a row.</p><pre>-- Batch 1<br>SELECT * FROM orders ORDER BY created_at DESC LIMIT 100 OFFSET 0;<br><br>-- Batch 2<br>SELECT * FROM orders ORDER BY created_at DESC LIMIT 100 OFFSET 100;</pre><p>A better option is <strong>key-based</strong> batching. No rows inserted in between batches would be skipped or duplicated. Also note that we omit the OFFSET entirely, so PostgreSQL won’t re-read all the rows before a given key — this saves a lot of time. Crucially, the ORDER BY query is only run against an indexed column where data is already sorted. If the same query is run against a non-indexed column, it would have severe performance consequences. Key-based batching is one of the most widely used approaches.</p><pre>-- Batch 1: Get the initial set<br>SELECT * FROM orders ORDER BY id ASC LIMIT 100;<br>-- Record the last ID from this batch (e.g., last_id = 100)<br><br>-- Batch 2: Start exactly where you left off<br>SELECT * FROM orders WHERE id &gt; 100 ORDER BY id ASC LIMIT 100;<br>-- Record the next last_id (e.g., last_id = 200)</pre><p>A third option is <strong>time-based batching</strong>, which uses timestamps to partition data. This is well-suited for scheduled reporting jobs — for example, “how many orders were placed in the last hour” — or pipelines that ship data to an analytics server every few hours.</p><pre>-- Batch for a specific hour<br>SELECT * FROM orders <br>WHERE created_at &gt;= &#39;2026-03-04 10:00:00&#39; <br>  AND created_at &lt; &#39;2026-03-04 11:00:00&#39;<br>ORDER BY created_at ASC;</pre><p>However, timestamps are a well-known source of subtle bugs in distributed systems. Even on a single server under high write load, multiple rows can share the same timestamp, making timestamp-based partitioning unreliable on its own.</p><p>Once you have chosen how to split your data, the next step is feeding those batches into a pipeline — commonly known as an ETL (or ELT).</p><h3>Extract-Transform-Load (ETL)</h3><p><strong>Extraction </strong>is capturing data. It could be a batch of data from a database, web scraped content, ERP systems, emails or any other unstructured format or structured format. <strong>Transformation</strong> converts the raw data into a useful format. This can include filtering, deduplication, encryption, column addition or removal, type conversions, and general data cleaning. The last step is to load or “dump” them somewhere. The destination is usually a data lake, warehouse or a lake-house. This is the domain of OLAP (analytical databases), where the goal is to generate summaries, reports and capture insights useful for directing business decisions. ETL pipelines also underpin machine learning workflows, fraud detection, and forecasting</p><p>There exists another architecture called ELT which is similar to an ETL in the meaning of terms. But they serve different purposes. An ELT loads the data first and then transforms it. This is useful in machine learning algorithms on the raw inputs. ELTs usually write data to data lakes whereas ETLs load data into data warehouses. For ELTs, both the raw and refined data exists on the same platform, organised into bronze, silver and gold layers. You can read more about ELT or ETL on <a href="https://www.ibm.com/think/topics/elt"><em>IBM’s docs</em></a>.</p><p>Common tooling in this space includes: <strong>Airbyte</strong>, <strong>Fivetran</strong>, and <strong>Apache Kafka</strong> for ingestion; <strong>Apache Spark</strong> and <strong>Databricks</strong> for transformation (cleaning, deduplication, joins, and parallel processing). For storage, popular data warehouses include <strong>Snowflake</strong>, <strong>Google BigQuery</strong>, and <strong>Amazon Redshift</strong>; major data lake solutions include <strong>AWS S3</strong> and <strong>Apache Hadoop.</strong></p><h3>Change Data Capture (CDC)</h3><p>A CDC is usually seen in contrast to ETL. A data pipeline moves data in batches and via jobs, this means the data fetched is somewhat stale. A change data capture system captures and streams changes in real time. The difference is analogous to HTTP polling versus WebSockets. ETL “polls” or queries for a batch of data, whereas a CDC “pushes” pieces of data.</p><p>CDCs can work in primarily two different ways. One is Trigger based while other is Log-based. <strong>Trigger based</strong> systems, trigger a piece of code execution whenever there are changes (INSERT/UPDATE/DELETE) made to a table. However too many triggers can incur a noticeable performance overhead.</p><p><strong>Log-based CDC</strong> monitors the database’s Write-Ahead Log (WAL) — also called a transaction log — which records every change made to the database. As soon as a new entry appears in the WAL, the CDC tool streams that event to the target system. This approach has minimal impact on database performance and is the preferred method at scale.</p><p>Most production CDC systems pair the log reader with a message queue. Debezium, for example, reads from the WAL and publishes events to Apache Kafka; downstream consumers (such as data warehouses) then read from the Kafka topic. Other widely used tools in this space include Airbyte (which wraps Debezium) and AWS DMS. Look up to <a href="https://www.youtube.com/watch?v=6VbRlQ0rL3I"><em>this video</em></a> for a deeper dive into Debezium or read <a href="https://airbyte.com/blog/change-data-capture-definition-methods-and-benefits"><em>Airbyte’s blog</em></a> for more.</p><h3>Foreign Data Wrappers (FDWs)</h3><p>An in-built way to handle data flow in PostgreSQL. With FDWs you can treat tables stored on other servers or even other database engines as if they were locally stored tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEuqpMdoGFAbZoDocIXXvw.png" /></figure><p>Before we look at the creation process, let us look at a simple query :</p><pre>SELECT * FROM foreign_app.users WHERE name = &#39;Alice&#39;;</pre><p>The “foreign_app” could be a different postgreSQL server, a S3 bucket, ElasticSearch, MongoDB or anything else. Yet, the way we wrote the query felt like looking up a local table. One key distinction from other ways of integration we have discussed so far is that a FDW does <em>NOT</em> pull copy data from remote sources. They establish a live connection, so queries always reflect the latest state of the foreign source. This removes the need to set up a full pipeline just to run a query against a few thousand rows.</p><p>That said, FDWs are not a replacement for ETL pipelines. They have several notable limitations. Wrappers are not as feature rich as any custom data pipeline. Firstly, FDWs run on memory, so if you try to query a million rows other queries on your main database might be affected. Another major drawback to wrappers : they don’t come with a retry mechanism. If a few rows fail due to random network blips, the entire query would fail. The third drawback to them is they can’t detect schema changes. Addition or removal of columns and tables must be handled manually.</p><p>Setting up an FDW involves three steps: (1) create a connection to the foreign server in a dedicated schema to avoid naming conflicts, (2) provide user credentials for authentication, and (3) define a proxy table that maps only the required columns. You can look up here for the code:<em> </em><a href="https://thoughtbot.com/blog/postgres-foreign-data-wrapper"><em>ThoughtBot’s blog</em></a><em>.</em> You can also read some more examples on <a href="https://supabase.com/docs/guides/database/extensions/wrappers/overview"><em>Supabase’s intro to FDWs</em></a>.</p><h3>Conclusion</h3><p>This post covered several of the most common approaches to moving data from point A to point B: batching, ETL, ELT, CDC, and FDWs. However, these are not all. As I was writing this blog I got to hear about half a dozen new concepts— data virtualization, data mesh, replication for backups and a few more. If any of these caught your interest, they’re worth digging into further.</p><p>Thanks for reading, see you soon on the other side of knowledge :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97cb5a0dffd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But What are Spatial Databases ?]]></title>
            <link>https://medium.com/@shekdivyanshu/but-what-are-spatial-databases-e50737632659?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50737632659</guid>
            <category><![CDATA[spatial-computing]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 14:51:00 GMT</pubDate>
            <atom:updated>2025-10-07T14:51:00.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>But What are Spatial Databases ?</h3><p>Ever thought how Uber finds cabs near you or how Google Maps suggests restaurants within 2 kilometre radius of your location ? I will try to cover the core ideas addressing these computational problems, often referring to the abstract mathematical topics that make them possible.</p><p><em>Note :</em> This is <em>not going to be a conventional, tutorial-style</em> kind of blog. I have included several references, because I simply believe they will explain the theoretical parts better than I ever could. My goal is simply to connect the dots and help you reach your “aha” moment. A little knowledge of core database concepts such as B-trees and Binary trees would be helpful.</p><p>Let&#39;s get straight to the point — given the world’s map how would you store it ? (And yes, for this exercise, we’re not entertaining the flat Earth theory, lol.) We will dive deeper into all the major data structures that make these possible. So let’s begin!</p><h4>R Trees</h4><p>Before we get into the details of R trees we need to understand what is meant by a <strong>Minimum Bounding Rectangle</strong>, or simply a MBR. A MBR is defined as the smallest rectangle (aligned to the axes) that completely <em>encloses</em> a spatial object — such as a point, line, polygon, or even a set of objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohJBFar2D08JJKHnpwFcgA.png" /><figcaption>Finding MBR for a polygon</figcaption></figure><p>Now a knowledge of what a B-tree (more specifically a B+ tree) is would be immensely helpful. Here is a quick guide for <a href="https://youtu.be/K1a2Bk8NrYQ">B trees 🔗</a>.</p><p>R trees are the <em>B+ trees for MBRs</em>. Let me break it down for you : Imagine starting with a very large minimum bounding rectangle (MBR) — one that covers a significant part (or even all) of the polygons in your dataset. This bounding rectangle becomes the root node of an R-tree and contains several child nodes.<br>Each child node is itself a smaller bounding rectangle, nested within the root, and each of these can in turn be a parent to more rectangles contained within them. Think of this as a hierarchy of bounding regions, where each level stores spatial objects grouped inside successively smaller rectangles.</p><p>A distinctive feature of R-trees compared to B+ trees is that in R-trees, the bounding rectangles (MBRs) for sibling nodes can <em>overlap</em> — there’s no strict separation as in B+ trees, where each range is completely partitioned and never overlaps.<br>This overlap means that when searching, a polygon might be covered by more than one bounding rectangle, so the search may sometimes need to follow multiple paths. For example, look at the overlap between R3 and R4 in the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NYctLvYDQk9ImFNs.png" /><figcaption>By Skinkie, w:en:Radim Baca — Own work, Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=9938400">https://commons.wikimedia.org/w/index.php?curid=9938400</a></figcaption></figure><p>You can further read the original paper by A. Guttman here : <a href="https://dl.acm.org/doi/10.1145/971697.602266">paper link 🔗</a>. PostGIS implements GIST (a custom spatial indexing structure) which is very similar to R-trees.</p><h4>Quadtrees</h4><p>Think of them as simple extension of the Cartesian Coordinate system. Divide the earth into grids where every individual grid cell would have its own unique identity. But how many grids to use — 4x4, 40x40 or 400x400 ?</p><p>Quadtrees offer an elegant solution through adaptive, recursive subdivision. Instead of using a fixed grid size, they dynamically adjust based on data<em> density</em>. This density is referred as <strong>load factor</strong> (X), this could be the number of users in a particular region, the number of active Uber drivers, or the count of restaurants within a quadrant.</p><p>Here’s the recursive process:</p><ol><li>Start with the entire map as one large quadrant</li><li>Check the load factor for that quadrant</li><li>If the load factor exceeds a predefined threshold, divide the quadrant into 4 smaller sub-quadrants</li><li>Repeat this process for each new sub-quadrant until every quadrant satisfies:</li></ol><blockquote>Load Factor ≤ Maximum Threshold for all quadrants</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*cia857amqMqvF11_.png" /><figcaption>By David Eppstein — self-made; originally for a talk at the 21st ACM Symp. on Computational Geometry, Pisa, June 2005, Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=2489019">https://commons.wikimedia.org/w/index.php?curid=2489019</a></figcaption></figure><p>Areas with higher load factor have higher density of grid cells. Areas with lower load have a lower density of grid cells. I believe the best way to learn this would be to get your hands dirty with writing some code (or atleast binge watching, I know you are lazy 😃) : <a href="https://youtu.be/kClPBNmTCf0">Code Your Own Quadtree 🔗</a> or you might like the <a href="https://youtu.be/OJxEcs0w_kE">Animated Quadtrees using p5.js 🔗</a></p><h4>Hilbert Curves</h4><p>The Hilbert curve was first described back in 1891 by David Hilbert. It is a space-filling curve, which means it is a 1D curve that passes through every point in a 2D space — technically, it’s an example of a mathematical <em>fractal</em>. Fractals ? Ever thought about fractional dimensions ? No! Right, cause we are sane humans and who would think that. Here is a crisp explanation for fractals (not really helpful for this article though) : <a href="https://youtu.be/gB9n2gHsHN4">Fractals Explained🔗</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/0*n_LCfvz7hbWxnv-b.png" /><figcaption>By Enormator — File:Hilbert.png, CC BY-SA 3.0, <a href="https://commons.wikimedia.org/w/index.php?curid=149101004">https://commons.wikimedia.org/w/index.php?curid=149101004</a></figcaption></figure><p>Now why even use these curves ? The reason is all the data structures we have seen already have poor performance for queries like : “<em>Hey Google! find Indian restaurants near me</em>”. Technically called <strong>range queries</strong>. Hilbert curve squishes the 2D map we have into a 1D line, such that points nearby in the map would also end up being closer on the line — in other words it <em>preserves spatial locality</em>. And it does so in an efficient manner. Doing range queries on a 1D line is a child’s play. It’s just like picking a set of numbers that are close together on a number line. To look into details of how we exactly do this refer to the following resource: <a href="https://youtu.be/3s7h2MHQtxc">Hilbert Curves Explained 🔗</a></p><p>Hilbert curves aren’t themselves any data structure, they are used for mapping locations. Hilbert Curves are often combined with other structures like R-trees. <a href="https://youtu.be/dSK-MW-zuAc">Coding Hilbert Curves with p5.js 🔗</a></p><h4>GeoHashing</h4><p>GeoHash are similar to quadtrees as they divide the earth into grid. But they do so evenly — 32x32 grid. And each cell is further divided into a 32x32 grid. The position of a cell is assigned with an alphanumeric character. So the number of character defines the level of nested cell we use. Also, as you might guess from the name <em>hash</em>, they are extremely fast for lookups. Geohashes are quite simple to implement, however they work only for point data and not spatial objects like lines or polygons. Databases like MongoDB and Elasticsearch rely on geohash for fast lookups and searching for nearby point. <a href="https://youtu.be/vGKs-c1nQYU">Geohash tutorial 🔗</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*cDlckxNwc2eeFdIq.png" /><figcaption>By Krauss — Own work, CC BY-SA 4.0, <a href="https://commons.wikimedia.org/w/index.php?curid=128655268">https://commons.wikimedia.org/w/index.php?curid=128655268</a></figcaption></figure><h4>Modern Spatial Indexing Libraries</h4><p>The article would be incomplete without talking about how Google and Uber actually scale to billions of devices. You might ask reasonably at this point why aren’t all the other classic data structures we discussed enough ?</p><p>Take R-trees, for example. While they are powerful for dynamic and multi-shape geometry searches in traditional GIS systems, they have a few key drawbacks when it comes to global-scale, cloud-native applications:</p><ul><li>Distributed scaling: Tree structures are tricky to partition or shard efficiently across thousands of servers, in other words they don’t scale horizontally.</li><li>Point lookup speed: For billions of points, grid/cell lookups are often orders of magnitude faster.</li></ul><p>This is where modern indexing libraries like Uber’s H3 and Google’s S2 come in. Both take a “divide the earth into cells” approach, but do so in a way that is globally accurate and ready for the cloud:</p><ul><li>H3 (Uber): Uses hexagonal hierarchies, giving cells with consistent neighbor relationships. Perfect for heatmaps, coverage, and fast range queries at internet scale.</li><li>S2 (Google): Maps the earth onto a cube (and then a sphere), recursively subdividing it into “spherical quads.” Optimized for keeping cell sizes consistent worldwide and for hierarchical queries over vast datasets.</li></ul><p>Also note that these libraries take into account the spherical nature of earth. A simple grid structure like quadtree generates distorted cells as we move towards the poles. These libraries are more useful for point data. These libraries are available as extensions to popular databases like Postgres, MongoDB, CockroachDB, etc,.</p><p>So this is where I would wrap up this article. A lot to swallow, I know, but hey! Now you can think more concretely when designing a fun-to-use software with vast spatial data to store. Please give a like to this article and make sure to follow me back. See you soon 😃!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50737632659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But What is Elasticsearch ?]]></title>
            <link>https://medium.com/@shekdivyanshu/but-what-is-elasticsearch-b0e5074f18b4?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0e5074f18b4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 17:38:35 GMT</pubDate>
            <atom:updated>2025-08-31T17:38:35.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>But What is Elasticsearch ?</h3><p>Ever wondered how search engines work ? How food delivery apps provide you with all the similar dishes that you search for ? Ever wondered about all that goes in finding out your favourite memes on Twitter ?</p><h3>But Why Elasticsearch ?</h3><p>Imagine having a blog website, with some thousands of users. On a random day, a user visits your website and searches for “cookies”, how will you return all the blogs containing the term “cookies” ? You might think why not run a simple Postgres command as :</p><pre>SELECT title, link FROM blogs WHERE title LIKE &quot;%cookies%&quot; ;</pre><p>Even though it might look easy, the problem grows with bigger data set. The string matching commands might take a few dozen seconds before returning all the matching blogs. This will bore your users to death ! But we have Indexes right ? Alas ! Indexes don’t work on string matching. Look at the following structure of a B-tree index storing string data :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmDwzEk7dgj840mEWapjWQ.png" /><figcaption>A simplistic model of B-tree storing strings</figcaption></figure><p>Imagine searching for “Dune”, because it might occur anywhere in the title, Postgres would scan all the titles in the database.</p><p>This is where a new kind of index an “inverted index” comes into play. Imagine mapping all the words alphabetically that occur in the title field to the document in which they appear. The process of extracting all the words is known as <em>tokenisation</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUkPZd5knmQKfP7uwWAKkQ.png" /><figcaption>A simple model for an inverted index</figcaption></figure><p>Now imagine searching for “Dune” in here. Because terms are already sorted, we exactly know which documents should be returned.</p><p>It was just one of the reasons why we need Elasticsearch, but there are a ton more. Let’s look at some major patterns where Elasticsearch outperforms any other database.</p><h3>But When Elasticsearch ?</h3><p><strong>Full Text Search</strong> → This probably is the main reason to use Elastic. You want lightning fast results even from complex queries run against long forms of text. Not just that, you can run queries against a large number of languages. Each language has its own set of words as well as grammar and tokenisation rules. Or there could be a mix of languages used in the same text (something very common on social media).</p><p>It gets more complicated when you think about what the user might actually search for. Imagine a user searches for blogs on ‘cookie’, shouldn’t we return the blogs containing ‘cookies’ ? So <em>stemming </em>different words to their root form is another task to perform. A search for ‘Feet’ should match blogs containing ‘foot’ and so on.</p><p><em>Synonyms </em>and <em>diacritics </em>introduce another challenge. Shouldn’t users asking for news regarding ‘soccer’ be shown recent news about ‘football’. Word ‘résumé’ should fetch details about ‘resume’.</p><p><strong>Handling Typos and Misspellings</strong> → Ever looked up a mis-typed word on Google only to find out that the results are exactly what you intended to look for. Or a text suggesting “Did you mean”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a24rQC-76tlnMkBemsk73w.png" /><figcaption>Typos are common.</figcaption></figure><p>These are handled via a technique called <em>Fuzziness </em>(a more technical term would be Damerau-Levenshtein distance). Obviously a simple SQL database will never provide users such an experience.</p><p><strong>Geo-based Queries</strong> → Searching for ‘Indian restaurants near me’ includes two layers of search — locality in radius of 3 kilometres around you, as well as an Indian restaurant. Elasticsearch also provides us with the ability to query on geographic location data. If you ever used Tinder, you might know about their distance filter, a tool based on elasticsearch. You can use geo-hashing for efficient queries, that provides result within a second.</p><p><strong>Aggregations</strong> → Aggregations in Elasticsearch let you go beyond search — you can count, group, average, or build charts over your data in real time, just like how Google Analytics shows you summaries instantly. Not just on textual data but it could be geographic locations too.</p><p><strong>Logging Data</strong> → A large number of organisations around the world use the ELK stack (elasticsearch, logstash, kibana) for running rapid queries and gaining insights into millions of logs that are generated everyday. For example, which servers hit more exceptions or how many user requests timed-out in the last hour.</p><p><strong>Semantic Search</strong> → This is different from normal full text search as it is based upon vector search. They use machine learning models to search based on <em>meaning</em> or content rather than <em>keywords</em>. Keyword search is still relevant, obviously, due to higher cost and latency of the vector models. The best approach is to start with keyword search, and if it doesn’t scale, go for a hybrid use of semantic and keyword searches.</p><h3>It’s All About Balance</h3><p>You will often hear the phrase “Recall vs Precision” when working with elasticsearch. The analogy is :</p><blockquote>A fisherman should cast his net wide, but never so much as to catch a shark</blockquote><p>If a user searches for ‘cookies’ we should show him all the relevant results related to cookies — baking a cookie, web cookies and anything else (recall). But showing results that make no sense to them is just bad enough (precision). That said, a lot of features in elasticsearch are dedicated to improving <em>relevance</em>, i.e., showing the best matches at the top, while partially matching results at the bottom of the result list. Guessing what the user intends to see is probably the most important thing you as a developer can do.</p><h3>Suggested Readings</h3><ol><li><a href="https://www.uber.com/en-IN/blog/evolution-of-ubers-search-platform/">Uber’s search evolution </a>— building an in-house elasticsearch alternative</li><li><a href="https://blog.bytebytego.com/p/how-tinder-recommends-to-75-million">Tinder’s algorithm &amp; geo-sharding</a></li><li><a href="https://youtu.be/dOyCq_mMtdI">Twitter search system architecture</a> (Video)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e5074f18b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multifield Queries With Elasticsearch — An Intuitive Guide]]></title>
            <link>https://medium.com/@shekdivyanshu/multifield-queries-with-elasticsearch-an-intuitive-guide-64c544a6c0b5?source=rss-1bef6b1b95c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/64c544a6c0b5</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[elastic-stack]]></category>
            <dc:creator><![CDATA[Divyanshu]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 09:53:17 GMT</pubDate>
            <atom:updated>2025-08-10T09:53:17.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multifield Queries With Elasticsearch — An Intuitive Guide</h3><p>Recently I was reading how to search multiple fields for a single query which the user provides. And it took me quite some time to grasp the real meaning behind the different approaches we have. Lets see if I can help you understand them within the next 10 minutes.</p><p>Imagine a user sending a single request to your search — “War &amp; Peace by Leo Tolstoy”, a single query but you must search two fields in your database — book title and the author. You might have an ‘Airbnb for Libraries’ start-up and the user goes like, “Libraries with Wi-Fi within 2 miles”. There are 3 main ways to query the data, so user gets the most relevant results, viz : Best Field, Most Fields and Cross Field queries.</p><h3>Best Field</h3><p>Use best fields when a match in any one field is sufficient, but a really <em>strong match in a single field should rank higher than weaker matches scattered across several fields</em>.</p><p>Imagine a user searches for “Java Programming” books on your app, and you run a multi-match query to search both the book title and the description fields to get the most relevant results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1I_pR5B7VdRya1a1U9nB2g.png" /><figcaption>We have 2 documents to search for the query</figcaption></figure><p>The issue is that a multi-match would add up the individual relevance scores of all matching fields. So for the first document, we have both the fields matching a part of the query. The title matches “Programming” while the description matches “Java” as well as “Program” (remember that the terms are analysed so “programming” also matches “programmers”). However, for the second field, we got only one matching field, the title. Now ideally the second document is more relevant and should be shown at the top of returned results. But alas, it wouldn’t be so, because the first document will have a higher score, just because of weaker matches across more fields than the second document.</p><p>This is when a dis-max (disjoint maximum) is useful — it calculates the relevance score of all fields, but the final score of the document is the maximum of all the individual fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a4lvSVJQWU1mGCktIbFcg.png" /><figcaption>The score calculated for each field is denoted next to the field. Note that the final score isn’t the sum, but the maximum of all scores for that document.</figcaption></figure><p>So the problem is now solved, we have successfully retrieved the most relevant field. However, you might agree that it seems too strict, even though description didn’t contributed to the final score, it should have an impact on the overall score. We can define another property “tie-breaker” inside the multi-match, which says, the overall score for the document will be the maximum of all field scores plus the score of other fields with a lower weightage. So if this weightage is 0.3, the score of description field will be multiplied by the factor 0.3 then added back to the title’s score. A weight of 1 would make this a simple multi-match query itself, as all the individual scores would be added up.</p><pre>{<br>  &quot;multi_match&quot; : {<br>    &quot;query&quot;       : &quot;Java Programming&quot;,<br>    &quot;type&quot;        : &quot;best_fields&quot;,<br>    &quot;fields&quot;      : [&quot;Title&quot;, &quot;Desc&quot;],<br>    &quot;tie_breaker&quot; : 0.3<br>  }<br>}</pre><p>You can play with more properties like a boost (boost the title field by a factor of 2) or minimum should match.</p><pre>{<br>  &quot;multi_match&quot; : {<br>    &quot;query&quot;                : &quot;Java Programming&quot;,<br>    &quot;type&quot;                 : &quot;best_fields&quot;,<br>    &quot;fields&quot;               : [&quot;Title^2&quot;, &quot;Desc&quot;],<br>    &quot;tie_breaker&quot;          : 0.3,<br>    &quot;minimum_should_match&quot; : &quot;50%&quot;<br>  }<br>}</pre><p>Or you can even go with the more verbose version if you need higher control over each field.</p><pre>{<br> &quot;dis_max&quot;: {<br>   &quot;queries&quot;: [<br>     {<br>       &quot;match&quot;: {<br>         &quot;Title&quot;: {<br>           &quot;query&quot;: &quot;Java Programming&quot;,<br>            &quot;minimum_should_match&quot; : &quot;50%&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;match&quot; : {<br>        &quot;Desc&quot; : {<br>          &quot;query&quot; : &quot;Java Programming&quot;,<br>          &quot;minimum_should_match&quot; : &quot;80%&quot;<br>        }<br>      }<br>    },<br>  ],<br>  &quot;tie_breaker&quot; : 0.3<br> }<br>}</pre><h3>Most Fields</h3><p>The core idea behind this could be stated as : <em>Match as many documents as possible (called “recall”), but push the documents that match the user’s query exactly to the top (called “precision”)</em>.</p><p>Usually this is done by keeping two or more versions of the same field you want to query. You index the same content into several fields, each with different analysis: one field might use stemming, another original text, another with shingles, diacritics, or synonym expansion. When searching, you query all these fields. If a document matches the query in multiple fields, matching in more fields boosts the relevance score. This allows users to get both broad matching (from stemmed/synonym-analyzed fields) and more precise boosts (from exact or shingled fields).</p><p>We start by keeping multiple version of the same title field. The description field is English analysed, so it would be stemmed and tokenised. But the ‘Desc.std’ filed will only be tokenised, so it will be stored exactly as indexed.</p><pre>{<br> &quot;Desc&quot;: {<br>   &quot;type&quot;: &quot;string&quot;,<br>   &quot;analyzer&quot;: &quot;english&quot;,<br>   &quot;fields&quot;: {<br>     &quot;std&quot;: {<br>       &quot;type&quot;: &quot;string&quot;,<br>       &quot;analyzer&quot;: &quot;standard&quot;<br>     }<br>   }<br> }<br>}</pre><p>Then we can write a simple most fields query as :</p><pre>{<br> &quot;query&quot; : <br>    {<br>      &quot;multi_match&quot; : {<br>         &quot;query&quot;  : &quot;Learning Coding&quot;,<br>         &quot;fields&quot; : [&quot;Desc^4&quot;, &quot;Desc.std&quot;],<br>         &quot;type&quot;   : &quot;most_fields&quot;<br>      }<br>    }<br>}</pre><p>So this would match as many documents as possible, because we have boosted the analysed “Desc” field by a factor of 4. But among the results that match the query exactly would be pushed to the top, due to the non-analysed “Desc.std” field.</p><h3>Cross Field</h3><p>The last two queries are what is known as “Field Centric”, because we were trying to match a query against each field value present in a document to check if it exists. The cross field query is known as “Term Centric”, because it checks whether a query value is present in all the fields combined. A name maybe broken into first, middle and last names, but the user would provide a single query like “James Bond” and we need to infer that user wants to search James as the first name while Bond as the last name. You might think why not query all the fields for the tokens “James’ and “Bond”. The one which matches both of them, should be most relevant. However, the following operation has some inherent flaws :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnRTDcTOoi5McKKZ0wI2ZA.png" /><figcaption>A multi-match would just work as a should query with all the fields.</figcaption></figure><p>Both documents match for country and city. The main difference comes at the field street. In the above example, even though document-1 is a more relevant match, both the documents would be scored almost same. Why ? Because the street in the second document also matches the word ‘Birmingham’. This is clearly not a good way to search.</p><p>One way would be to use the “copy_to” property in the index, to copy the Country, city and street as a single field called “address” inside the document. However it is good only if we know the user will make a cross field request at the time of indexing.</p><p>A cross field however works at query/search time :</p><pre>&quot;mutli_match&quot; : {<br>  &quot;query&quot; : &quot;England Birmingham Baker&quot;,<br>  &quot;type&quot; : &quot;cross_fields&quot;,<br>  &quot;fields&quot; : [&quot;country&quot;, &quot;city^2&quot;, &quot;street&quot;],<br>}</pre><p>You can add a minimum-should-match property too. Also a boost to the city would mean that all exact matching documents would be at the top, and those with the same city would be given a higher score too.</p><p>Here is how the cross field query works differently as compared to the most or best fields :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEjKsGh_aSfj17EpZ4Cx-Q.png" /><figcaption>Notice that same word goes for three different field. Rather than 3 words going for same field.</figcaption></figure><p>So now the first document will match a should clause in all the three cases. Whereas the second document would match only the “England” and “Birmingham” should cases.</p><p>You can read more about how cross field query blends inverse document frequencies in official documentations or just ask your favourite AI helper.</p><h3>Conclusion</h3><p>Knowing what and how the user is likely to query in your application is vital for returning the most relevant results. We looked at 3 ways you can modal your searches to return what the user might be looking for in different scenarios.</p><p>If you liked the article please drop a like and subscribe for more tech savvy yet humanly understandable blogs 😊 !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64c544a6c0b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>