<?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 Barış Beydemir on Medium]]></title>
        <description><![CDATA[Stories by Barış Beydemir on Medium]]></description>
        <link>https://medium.com/@BarisBeydemir?source=rss-b618bd297dc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YGqVCibS97r_swZteNqk9A.jpeg</url>
            <title>Stories by Barış Beydemir on Medium</title>
            <link>https://medium.com/@BarisBeydemir?source=rss-b618bd297dc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:03:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@BarisBeydemir/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PostgreSQL’de Yüksek Erişilebilirlik: Active-Active vs Active-Passive, Debezium ve WAL/LSN]]></title>
            <link>https://medium.com/@BarisBeydemir/postgresqlde-y%C3%BCksek-eri%C5%9Filebilirlik-active-active-vs-active-passive-debezium-ve-wal-lsn-9477824cf72f?source=rss-b618bd297dc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9477824cf72f</guid>
            <dc:creator><![CDATA[Barış Beydemir]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 13:58:28 GMT</pubDate>
            <atom:updated>2025-10-14T14:59:12.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66GBfz7I2nsrgsiOUv639w.png" /></figure><h3><strong>Aktif‑Aktif Mimarisi (Active‑Active)</strong></h3><p>Birden fazla node’un eş zamanlı olarak aktif çalıştığı, yükün paylaşıldığı, yüksek erişilebilirlik, performans ve ölçeklenebilirlik sağlayan sistemler.</p><p><strong>Kilit Noktalar:</strong></p><ul><li><strong>Yük Dengelemesi (Load Balancing)</strong></li><li><strong>Yüksek Erişilebilirlik (HA)</strong></li><li>​​<strong>Hızlı Ölçeklenebilirlik</strong></li><li><strong>Veri Tutarlığı ve Karmaşıklık</strong></li></ul><h3>Aktif‑Pasif Mimarisi (Active‑Passive)</h3><p><strong>Tanım:</strong> Bir node aktif olarak hizmet verirken diğer node’lar standby (yedek) modundadır; yalnızca birinci node başarısız olursa pasif node aktif hale geçer.</p><p><strong>Kilit Noktalar:</strong></p><ul><li><strong>Yedeklilik (Redundancy)</strong></li><li><strong>Basitlik ve Yönetilebilirlik(</strong>Tek bir aktif node nedeniyle yapı daha sade ve yönetimi daha kolay)</li><li><strong>Failover Süresi</strong></li><li><strong>Güçlü Tutarlılık(</strong>Yazma işlemi yalnızca tek bir node’da gerçekleştiği için tutarlılık daha fazladır)</li></ul><h3>Master — Standby Replica — Replica (Tek Master, Çoklu Replica)</h3><p><strong>Master (Primary):</strong> Hem okuma (read) hem yazma (write) işlemlerini gerçekleştirir; sistemin tek yazılabilir noktasıdır.</p><p><strong>Standby Replica (Hot veya Warm):</strong></p><ul><li><em>Hot Standby:</em> Sadece okuma işlemleri yapar ama streaming replication alarak veri güncel tutulur.</li><li><em>Warm Standby:</em> Bağlantı kabul etmez, yalnızca master çökmesi durumunda devreye girer.</li></ul><p><strong>Streaming Replication (Fiziksel):</strong> Master’ın Write-Ahead Log’larını (WAL) real-time olarak standby’lara göndererek veri tutarlılığı ve yüksek erişilebilirlik sağlanır; mod ister senkron ister asenkron olabilir.</p><p><strong>Failover Süreci:</strong> Master çökerse, standby promote edilerek yeni master olur.</p><p>Yüksek Erişilebilirlik için <strong>Active‑Active </strong>mimarisi çift master(multi-master) lı yapı gerektirdiği için maalesef her teknolojide kullanılamıyor.</p><h3>PostgreSQL, Çift-Master (Multi-Master) Olarak Çalışamaz</h3><p><strong>Core Destek Eksikliği:</strong> PostgreSQL çekirdeğinde native multi-master (eş-zamanlı write yapılabilen birden fazla master) desteği yoktur.</p><p><strong>Tutarsızlık ve Çakışmalar (Conflict):</strong></p><ul><li>Birden fazla master’da a conflict riski artar. Senkronizasyon ve conflict çözümü genellikle performansı düşürücüdür.</li><li>Multi-master sistemler genellikle “loose” tutarlılık sağlar, ACID garantileri zayıflar; bu da yüksek hata potansiyeli oluşturur.</li></ul><p><strong>Özetle</strong>: Aktif‑aktif yapı doğrudan uygulanamasa da, tek master + standby replikasyon + otomatik failover mekanizmalarının hızlı çalışması, sistemin yüksek erişilebilirlik beklentisini karşılaması için önemlidir.</p><p>Bunlarla beraber system designınınzda doğrudan postgresql in masterına bağlı olarak çalışması gereken sistemler varsa (Debezium gibi)onların da bu postgre failover durumuna hızlı adapte olması gerekir.</p><p><strong>Debezium Nedir?</strong></p><p>Debezium, açık kaynaklı bir Change Data Capture (CDC) platformudur. Veri tabanlarındaki satır düzeyindeki değişiklikleri izleyerek bunları uygulamaların dinleyebileceği kafka tabanlı event stream’lerine dönüştürür.</p><p>​​<strong>Genel Amaç ve Mimari</strong></p><p>Debezium; insert, update, delete işlemlerini transaction log’ları üzerinden (örneğin PostgreSQL için WAL) okuyarak Kafka topic’lerine yazar. Uygulamalar bu topic’leri tüketerek değişimlere tepki verebilir.</p><h3>Debeziumun bu görevi üstlenirken verdiği 2 garanti vardır</h3><ul><li><strong>At‑least‑once teslimat (en az bir kez teslim):</strong> Debezium, her değişiklik olayının mutlaka iletileceğini garanti eder; ancak bir hata veya yeniden başlatma durumunda bazı kayıtlar birden fazla kez gönderilebilir (çift teslimat riski).</li><li><strong>Sıralı teslimat (ordering):</strong> bir tablo için tüm event’leri tek bir Kafka topic’ine yazar ve bu topic’teki event’ler, veritabanındaki commit sırasına göre sırayla gelir. Bu, topic tek bir partition olduğunda tam sıralama garantisi sağlar</li></ul><p>​​Debezium, PostgreSQL’deki <strong>logical replication slot</strong> mekanizmasını doğrudan kullanır.</p><p><strong>PostgreSQL’de logical replication slot, WAL (Write-Ahead Log) girdilerinin silinmemesini sağlar. Debezium, bu slot üzerinden WAL’daki değişiklikleri okur ve Kafka gibi sisteme aktarılmasını sağlar.</strong></p><p><strong>Slot Tipleri:</strong></p><ol><li><strong>Physical (Streaming) Replication Slot:</strong> Fiziksel silindirler üzerinden veri replikasyonu için kullanılır; genellikle tam replikasyon senaryolarında.</li><li><strong>Logical Replication Slot:</strong> Row-level değişiklikleri mantıksal olarak takip eder — Debezium’un tercih ettiği tür budur, çünkü satır bazında değişim (CDC) sağlar.</li></ol><p>Slot’taki Veriler: Neyi Saklar ve Nasıl Görüntülenir?</p><p>PostgreSQL normalde WAL segmentlerini bir süre sonra temizler. Ancak bir logical replication slot aktif olduğu sürece gerekli WAL segmentlerinin silinmesini engeller; böylece Debezium bağlantısı kesilse bile verileri kaçırmaz.</p><p>WAL (Write-Ahead Log) Nedir?</p><p>​​WAL, veritabanı değişikliklerinin log dosyasına yazıldığı bir mekanizmadır. ​​Yani, diske gerçek veritabanı verisi yazılmadan önce önce WAL’a not edilir. Bu sayede veri tutarlılığı ve sistem güvenilirliği sağlanır.</p><h4>Örnek wal logları</h4><p>Örnek query<br><strong><em>SELECT * FROM pg_logical_slot_get_changes(‘debezium_slot’, NULL, NULL, ‘include-xids’, ‘1’);</em></strong></p><p>Örnek çıktı:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIOTr4Jk520_scFfdCJNag.png" /></figure><p>location: Her bir işlemin log içindeki LSN adresi.</p><p>xid: Transaction ID.</p><p>data: İşlemin detayları — hangi tablo, hangi satır; insert/update/delete ve değişiklik öncesi/seks sonrası değerlerle birlikte.</p><blockquote>WAL’daki kayıtlar yazıldıktan sonra, diske “flush” edilir; yani kalıcı hale getirilir.</blockquote><h4>Logical replication slot örnekleri</h4><p>slotlarınızı görebilmek için:</p><p><strong><em>SELECT slot_name, plugin, slot_type, database, active, restart_lsn, confirmed_flush_lsn FROM pg_replication_slots;</em></strong></p><p>Tipik çıktı</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQ5PyBvPGHTVFQ_kfAZ3ng.png" /></figure><blockquote>Db kayıtlı olan slotlardan restart_lsn i en önce olan kaydın restart_lsn değerinden önce olan bütün wal kayıtlarını tutmaz siler.</blockquote><p><strong>LSN (Log Sequence Number):</strong></p><p>Her WAL girdisinin benzersiz adresidir. Mesela 0/1700B50 gibi ya da yukarıdaki wal örneğindeki 5A/200D3500 gibi. Debezium, bu LSN’leri okudukça ilerler; böylece değişiklikleri sırasıyla kesintisiz okumaya devam eder.</p><p>​​</p><p><strong>Slot un içindeki confirmed_flush_lsn ve restart_lsn nedir?</strong></p><p>Confirmed_flush_lsn:</p><p>Bu, Debezium (ya da diğer logical decoding tüketicisi) tarafından <strong>başarıyla okunan ve Kafka gibi downstream sisteme gönderilen WAL pozisyonudur</strong>.</p><p>Restart_lsn:</p><p>Hâlâ işlemde olan <strong>tamamlanmamış transaction’ların başlangıcından önceki</strong> LSN’dir. Yani slot hala bu lsn den sonraki wal lara ihtiyaç duyabilir</p><p>Bu değer, <strong>PostgreSQL’in saklaması gereken en eski WAL segmentini</strong> belirler.</p><p>​​Debezium, WAL’ları “batch” halinde okuyor: belirli bir LSN (Log Sequence Number) aralığını alıyor, transaction’ları çözüyor, Kafka’ya push ediyor ve bunları başarılı yazdıkça confirmed_flush_lsn değerini güncelliyor.</p><p>Örnek:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjbarxpKFPj6uhyF3O7DOw.png" /></figure><p>Bu şekilde bir senaryomuz olduğunu düşünelim, Buradaki wal loglarını debezium batch bir şekilde okumuş olsun</p><p>Örnek Wal kayıtları</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*UvHhDTUwAM_5VN5tW6Y3Vw.png" /></figure><h3>1. Adım — Transaction B (0/A6)</h3><ul><li><strong>Debezium</strong>, tx B içindeki 0/A2, 0/A4, 0/A6 işlemlerini alır ve Kafka’ya gönderir.</li><li>Kafka’ya başarılı şekilde iletildikten sonra, PostgreSQL’deki replication slot’ta confirmed_flush_lsn = A/A6 olarak güncellenir.</li></ul><p>A henüz tamamlanmadığı için restart_lsn, restart_lsn hâlâ ilerleyemez (A/A0) kalır; çünkü hala tamamlanmamış transaction’lara ihtiyaç duyulabilir.<a href="https://www.morling.dev/blog/postgres-replication-slots-confirmed-flush-lsn-vs-restart-lsn/?utm_source=chatgpt.com"> Örnek olarak transaction a nın 0/A6 dan önceki wal loglarına hala ihtiyaç vardır.</a></p><h3>2. Adım — Transaction A (A/A8)</h3><ul><li>tx A’deki 0/A1, 0/A3, 0/A5, 0/A7, 0/A8 çekilir ve Kafka’ya gönderilir.</li><li>Onaylandığında confirmed_flush_lsn = 0/A8 olur.</li><li>Artık tüm transaction’lar tamamlandığı için restart_lsn da <strong>A/A8</strong> değerine ilerleyebilir; böylece PostgreSQL bu noktaya kadar olan WAL segmentlerini sorunsuzca silebilir</li></ul><p><strong>Genel Tabloyla Dağılım</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*79TR-EZs2KqG87xEvvtV1Q.png" /></figure><p>Bu şekilde eşzamanlı transaction’ların yönetilmesinin birkaç önemli sonucu vardır:</p><ul><li>Logical replication tüketicileri, aldıkları event’lerin LSN’lerinin <strong>kesinlikle artış yönünde</strong> olacağına güvenemez. Çünkü transaction’lar commit sırasına göre sunulur ve bu durumda <strong>daha düşük LSN’e sahip event’ler</strong> <strong>daha yüksek LSN’li event’lerden sonra</strong> yayınlanabilir. Ancak sadece (commit_lsn, lsn) çifti için <strong>sıralı artış garantisi</strong> vardır. Yani: commit LSN’ler <strong>azalmayan</strong> bir sıraya, ve bir transaction içerisindeki event’lerin LSN’leri de <strong>azalmayan</strong> sıraya sahiptir.</li><li>Büyük veya uzun süre açık kalan transaction’lar, replication slot’un restart_lsn değerinin ilerlemesini engeller ve bu yüzden WAL’ların gereğinden fazla tutulmasına yol açabilir. Bu yüzden mümkünse bu tür transaction’lardan kaçınılmalıdır.</li></ul><p>Peki logical replication motoru, WAL’daki COMMIT eventiyle karşılaştığında hangi event’leri yayınlayacağını nasıl belirliyor? İşte burada “reorder buffer” adında bir veri yapısı devreye giriyor. Bu yapı, WAL’dan gelen tüm event’leri transaction id bazında toplar. Commit eventi işlendiğinde, o transaction’a ait tüm event’ler buffer’dan çekilir ve tüketiciye iletilir. Böylece WAL içinde pahalı bir arama (seeking) işlemi gerektirmez.</p><p>Reorder buffer, büyük transaction’lar için diske taşma (spill) yapabilir. Varsayılan limit 64 MB’dır ve logical_decoding_work_mem ile ayarlanabilir. Disk spill olduğunda ek disk I/O’su gerekebilir, bu yüzden pg_stat_replication_slots görünümüyle spill miktarını izlemeniz faydalı olur.</p><p>confirmed_flush_lsn her zaman restart_lsn ile karşılaştırıldığında <strong>daha yüksek veya eşit</strong> değerde olur. restart_lsn ≤ confirmed_flush_lsn</p><p>Şimdi asıl konumuz olan failover senaryosunda sistemizin recovery süresini kısaltmaya dönersek, eğer debezium içiren bir sistemimiz varsa ve restart olmuşsa:</p><p>Kafka Connect’in <strong>offset topic</strong>’inde saklanan en son işlenmiş LSN bilgisini kullanarak <strong>replication slot</strong>’u buna göre <strong>“rewind”</strong> edebiliyor.</p><p>​​işleyiş şu şekilde:</p><ol><li>Debezium, Kafka Connect’in internal offset topic’ine periyodik olarak <strong>son işlenen LSN ve transaction ID</strong> bilgisini yazar.</li><li>Connector yeniden başlatıldığında, bu offset bilgilerini okur.</li><li>Bu LSN bilgisine göre PostgreSQL’daki <strong>replication slot’u yeniden konumlandırır (rewind)</strong>.</li><li>Sonrasında WAL okumaya bu konumdan devam ederek, event akışına kaldığı yerden devam eder</li></ol><h4>Debezium’da ‘Rewind’ Durumunda Hangi LSN Geri Alınır?</h4><p>Debezium connector yeniden başlatıldığında <strong>confirmed_flush_lsn</strong> değerine bakar (Kafka Connect offset topic üzerinden okunur) ve WAL okumaya o noktadan devam eder. Bu işlem, replication slot’un bulunduğu PostgreSQL tarafındaki restart_lsn değerini değiştirmez.</p><p>Yani “rewind” işlemi Debezium’un <strong>confirmed_flush_lsn</strong>’i esas alır; <strong>restart_lsn</strong> üzerindeki bir değişiklik Debezium tarafından yapılmaz.</p><p>Zaten eğer restart_lsn i değiştirseydi. Postgresql restart_lsn den önceki wal kayıtlarının korunduğunu garanti etmediği için onlar silinmiş de olabilirdi ve debezium wal loglarını okuyamazdı.</p><h3>Patroni ve etcd: Otomatik Failover’ın Omurgası</h3><p>​​</p><h4>Patroni + etcd ile PostgreSQL HA</h4><ul><li><strong>Patroni, PostgreSQL için lider seçimi, otomatik failover ve mastera terfi gibi işlemleri yöneten bir HA yöneticisidir. etcd (veya Consul/Zookeeper) üzerinde paylaşılan bir konfigürasyon deposu (Distributed Configuration Store — DCS) kullanır. etcd, cluster bilgisi, sağlık durumu ve o anki master node gibi verileri tutar ve Patroni’lerin bu verileri kullanarak koordine olmasını sağlar.</strong></li><li><strong>etcd’nin ayrı sunucularda çalıştırılması önerilir. Patroni ve PostgreSQL ile aynı sunucuda olması, yük altında etcd’nin zamanında yanıt verememesine; bu da yanlış failover veya liderin düşürülmesine (fencing) neden olabilir.</strong></li></ul><h4>Patroni, Failover ve Logical Replication Slot Yönetimi</h4><ul><li>PostgreSQL’de logical replication için kullanılan <strong>replication slot</strong> yalnızca primary node’da oluşturulur; failover durumunda downstream sistemler bu slot’u göremez.</li><li><strong>Patroni versiyon 2.1.0 ve sonrası</strong>, bu slot bilgisini standby node’lara da kopyalayarak failover sonrası downstream bağlantılarının sorunsuz devam etmesini sağlar. Slot ilerlemesini (LSN) de takip eder.</li></ul><h3>Debezium ile Triggering ve Failover Hassaslığı</h3><ul><li>Debezium, <strong>logical replication slot</strong> üzerinde çalışır ve primary PostgreSQL’e bağlanır. Failover sırasında bağlandığı primary node değiştiğinden, yeni aktif nodda yeniden slot ve publication’ın doğru yönetilmesi çok önemlidir.<a href="https://stackoverflow.com/questions/69406349/debezium-with-rds-postgres-and-master-replica-failover?utm_source=chatgpt.com">Stack Overflow</a></li><li>PostgreSQL 16 ve sonrası versiyonlarda <strong>replica üzerinde slot oluşturabilirsiniz</strong>, ancak bunlar primary ile senkron değildir. Failover sonrası manuel senkronizasyon gerekebilir.<a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html?utm_source=chatgpt.com">debezium.io</a></li><li>Ayrıca Debezium’un aktif kümelerde <strong>hot standby</strong> benzeri bir yedeği yoktur. Kafka Connect, connector’un yeniden başlatılması zaman alabilir — bu da kısa süreli data akışı kopmalarına yol açabilir.<a href="https://debezium.io/blog/2020/02/25/lessons-learned-running-debezium-with-postgresql-on-rds/?utm_source=chatgpt.com">materialize.com+3debezium.io+3debezium.io+3</a></li><li>Replication slot’ta WAL birikimini önlemek için<strong> izleme ve slot temizliği</strong> gibi operasyonel önlemler almak gerekir.<a href="https://www.morling.dev/blog/mastering-postgres-replication-slots/?utm_source=chatgpt.com">morling.dev</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*dxiTBzefi8DT5VluDHSbiw.png" /></figure><h3>Uygulama Akışı (Önerilen)</h3><ol><li>İki AZ’lı yapı: Zone A’da master (+Patroni), Zone B’de replica (+Patroni).</li><li>Patroni + etcd kullanarak quorum tabanlı leader seçimi.</li><li>Logical replication slot’ların Patroni tarafından standbya da kopyalanması ve güncellenmesi.</li><li>Failover durumunda Patroni yeni replica’yı otomatik olarak master’a çevirir. Debezium bağlantısı için, Yeni master’a manuel ya da HAProxy gibi bir load-balancer ile yönlendirme yapılmalı.</li><li>Debezium tarafı için:</li></ol><ul><li>PostgreSQL 16+ ise replica’da slot yapılandırma + periyodik senkronizasyon.</li><li>Connector-unavailability süresini minimize için yedek Debezium instance’ları veya container orchestration ile hızlı restart sağlamayı düşünün.</li></ul><blockquote>WAL/slot yönetimi için monitoring ve cleanup mekanizmaları entegre edilmeli.</blockquote><p><strong>Quorum tabanlı lider seçimi (quorum-based leader election) nedir?</strong></p><p>Quorum tabanlı lider seçimi, bir kümedeki en az çoğunlukta (quorum) düğümün (node) aynı fikirde olması gerektiği bir mekanizmadır. etcd gibi dağıtık sistemlerde, yeni bir liderin seçilmesi veya sistem durumunun güncellenmesi için bu çoğunluğun onayı gerekir. Örneğin 3 düğümlü bir etcd kümesinde, quorum değeri “(n/2) + 1 = 2”’dir; yani en az iki düğüm aktif ve anlaşma içinde olmalı ki lider atanabilsin veya güncelleme yapılabilsin. Bu, bölünmüş beyin (split‑brain) gibi tutarsızlıkların önüne geçer.</p><p>​​<strong>Replication slot’ların Patroni tarafından standby’lara kopyalanması, sürekli mi yapılır yoksa sadece failover anında mı?</strong></p><p>Patroni, replication slot’ları sadece bir kez değil, sürekli olarak standby’lara kopyalar ve günceller. Süreç şöyle işler:</p><ul><li>Patroni konfigürasyonunda <strong>“slots”</strong> bölümünde kalıcı (permanent) logical replication slot tanımlandığında, bu slot ilk olarak primary üzerinde oluşturulur.</li><li>Ardından Patroni, bu slot bilgisini standby’lara da kopyalar.</li><li>Sadece kopyalamakla kalmaz; ayrıca <strong>LSN (log sequence number)</strong> değerini de primary ile paralel olacak şekilde standby’larda günceller — bu sayede standby’lar, failover sonrası hazır durumda olurlar.</li></ul><h3>Patroni Her Bir PostgreSQL Instance Üzerine Kurulur — Doğru Mu?</h3><p>Evet, doğru. Patroni, <strong>her PostgreSQL düğümünde (instance)</strong> kurulur ve çalışır. Her Patroni örneği, kendi PostgreSQL servisini izler ve kümenin durumu hakkında bilgi toplar. Etcd gibi bir Dağıtık Konfigürasyon Deposu (DCS) ile bu bilgileri paylaşarak liderlik seçimi ve failover işlemlerinde aktif rol alır.</p><h3>Etcd Olmadan Bu Yapı İşler Mi? Yoksa Koordinasyon Alanında Ne Olur?</h3><ul><li>Patroni, <strong>dağıtık lider seçimi (“leader election”)</strong> ve failover karar mekanizması için bir tür mutex/kilit yapısına ihtiyaç duyar. Bu rolü ise <strong>etcd</strong>, <strong>Consul</strong>, <strong>ZooKeeper</strong> ya da <strong>RAID tabanlı alternatifler</strong> (örneğin pysyncobj gibi) üstlenir<a href="https://github.com/patroni/patroni?utm_source=chatgpt.com"> </a>.</li><li>Yani yalnızca PostgreSQL + Patroni yüklü olsa bile, kimin lider olduğunu ve failover durumunda kimin master olacağını belirleyecek merkezi koordinasyon olmayacağı için <strong>otomatik failover ve split-brain önleme mekanizması çalışmaz</strong>.</li><li>Bu yüzden, bir DCS <strong>olmaksızın</strong> Patroni ne kadar yüksek erişilebilir olursa olsun, gerçek anlamda kararlı ve güvenli bir HA yapı kurmak mümkün değildir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*x1gk4Bmq54JYB7xhMWqFyw.png" /></figure><p>peki wal logları sadece primary db de yani sadece master da mı oluyor, wal logları replicalarda da olur mu</p><p>​​</p><h3>WAL Logları Sadece Primary’de üretilir</h3><ul><li>PostgreSQL, tüm değişiklikleri önce WAL’a (pg_wal dizininde) yazar. Bu log, sistem çökse bile tutarlılığı korumak için kullanılır.</li><li>Standby (replica) sunucular, kendi veritabanlarında yalnızca WAL loglarını <em>uygulamak</em> için bir hedef dizinine sahip olur ama bu logları üretmezler.</li></ul><h3>Standby’lara WAL Streaming Replikasyonu</h3><ul><li><strong>Streaming replication</strong> kullanıldığında, primary WAL segmentlerini doğrudan standby’lara gönderir ve standby’lar bunları kendi taraflarında replay eder. Bu şekilde veriler blok düzeyinde eşitlenmiş olur.</li><li>Streaming replication, log shipping’e göre genelde daha düşük gecikme ve daha gerçek zamanlı senkronizasyon sağlar.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9477824cf72f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Turbocharging PostgreSQL with PgBouncer]]></title>
            <link>https://medium.com/@BarisBeydemir/turbocharging-postgresql-with-pgbouncer-7ec784dda605?source=rss-b618bd297dc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec784dda605</guid>
            <dc:creator><![CDATA[Barış Beydemir]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 21:41:01 GMT</pubDate>
            <atom:updated>2025-07-23T21:41:01.834Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL is a powerful database, but it doesn’t handle lots of connections well. Every client connection uses memory and CPU. When your app grows, too many connections can slow things down or even crash the database. You may see errors like “too many clients” and experience big slowdowns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SISfnL2uO00vFaarauPmdw.png" /></figure><p>PgBouncer helps with this. It’s a small, fast tool that sits between your app and PostgreSQL. It pools connections, so PostgreSQL doesn’t get overwhelmed. In this guide, you’ll learn what PgBouncer does, when to use it, and how to set it up in AWS for a real performance boost with e demo.</p><p><a href="https://github.com/ituitis-beydemir18/pgbouncer-performance-test"><em>https://github.com/ituitis-beydemir18/pgbouncer-performance-test</em></a></p><h3>Why Too Many Connections Are a Problem</h3><p>Modern apps (microservices, web servers, serverless) open many connections. PostgreSQL creates a new process for each connection, using memory and CPU. If you exceed max_connections (default is around 100), PostgreSQL slows down or rejects new clients.</p><p>A connection pooler like PgBouncer reuses a small number of DB connections to serve many clients. This reduces resource usage and keeps your DB fast and stable.</p><h3>What is PgBouncer?</h3><p>PgBouncer is a lightweight connection pooler for PostgreSQL. It accepts all client connections and opens only a few to the actual database. This keeps the number of real DB connections low.</p><p>PgBouncer runs as a small service, often on port 6432. It is very efficient and easy to set up. It’s great for apps with high traffic.</p><h3>Why PgBouncer Stands Out</h3><ul><li><strong>Fast &amp; Lightweight:</strong> Written in C. Doesn’t inspect queries. Runs on one core with minimal resources.</li><li><strong>Connection Reuse:</strong> Keeps a small pool of connections and reuses them.</li><li><strong>Central Management:</strong> One point of access. Set rules once, and all apps follow them.</li></ul><h3>Pooling Modes in PgBouncer</h3><p>PgBouncer has 3 pooling modes:</p><h4>1. Session Mode</h4><ul><li>Each client gets a dedicated DB connection for the full session.</li><li>Connection stays reserved until the client disconnects.</li><li>Acts like a normal DB connection.</li></ul><p><strong>When to use:</strong> If your app needs temp tables, SET commands, session-level features, or uses things like LISTEN/NOTIFY.</p><p><strong>Example:</strong> Spring Boot + HikariCP already uses a pool. Adding PgBouncer in session mode is often redundant.</p><p><strong>Important:</strong> Set server_reset_query = DISCARD ALL in pgbouncer.ini to avoid session state leaking between clients.</p><p><strong>Example case:</strong></p><ul><li><strong>App A (old legacy system)</strong> runs long queries and sets SET statement_timeout = 1000; to prevent runaway queries.</li><li><strong>App B (modern REST API)</strong> sends short INSERT queries.</li></ul><p>If App A uses a connection and goes idle <strong>without disconnecting</strong>, then PgBouncer might reuse that same connection for App B. But since statement_timeout = 1000 is still set from App A, App B’s query will unexpectedly fail if it takes longer than 1 second.</p><p>➡️ Result:<br> Even though App B sent a normal request, it gets an error like:</p><ul><li>ERROR: canceling statement due to statement timeout</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIXaVYWCd9oXnjia9Np6YA.jpeg" /></figure><p>✅ Setting server_reset_query = DISCARD ALL ensures PgBouncer clears all session-level settings before reassigning the connection to another client.</p><p><strong>When to use:</strong> If your app needs to keep session state or uses features like SET, temp tables, LISTEN/NOTIFY, or advisory locks.</p><h4>2. Transaction Mode</h4><ul><li>Each transaction gets a DB connection from PgBouncer.</li><li>After COMMIT, the connection returns to the pool.</li></ul><p><strong>Limitations:</strong></p><ul><li>No session-level features like SET, temp tables, or session locks.</li><li>Use SET LOCAL if you must change settings.</li><li>Prepared statements might break unless you tweak your client (e.g., set prepareThreshold=0 or use emulation).</li><li>Not ideal if your app depends on persistent session behaviors.</li></ul><p><strong>When to use:</strong> Best choice for most apps. It’s the default on platforms like Heroku because it offers great scalability.</p><h4>3. Statement Mode</h4><ul><li>Connection is returned after each SQL statement.</li><li>No transactions allowed. BEGIN ... COMMIT will fail.</li><li>Use only if your app runs one statement at a time with no session state.</li></ul><p><strong>When to use:</strong> Rarely. Only for key-value lookups or simple read-only queries.</p><h3>Java Spring Example</h3><pre>@RestController<br>public class MyController {<br><br>    @Autowired<br>    private MyService service;<br><br>    @GetMapping(&quot;/doWork&quot;)<br>    public ResponseEntity&lt;String&gt; doWork() {<br>        service.handleRequest();<br>        System.out.println(&quot;Service is done. Now logging and async tasks...&quot;);<br>        simulateOtherWork();<br>        return ResponseEntity.ok(&quot;Done!&quot;);<br>    }<br><br>    void simulateOtherWork() {<br>        try { Thread.sleep(2000); } catch (InterruptedException ignored) {}<br>    }<br>}<br><br>@Service<br>public class MyService {<br><br>    @Autowired<br>    private MyRepository repo;<br><br>    @Transactional<br>    public void handleRequest() {<br>        repo.insertSomething();<br>    }<br>}<br><br>@Repository<br>public interface MyRepository extends JpaRepository&lt;MyEntity, Long&gt; {<br>    @Modifying<br>    @Query(&quot;INSERT INTO my_table (data) VALUES (&#39;x&#39;)&quot;)<br>    void insertSomething();<br>}</pre><h3>Behavior Table: Session Mode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWXGC3pr5GY_DX8dfSXttQ.png" /></figure><p><strong>Note:</strong> Connection is held even after transaction ends, which is inefficient.</p><h3>Behavior Table: Transaction Mode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*X00cerXvwvMQBCKFbW-pUg.png" /></figure><h3>Statement Pooling Mode Behavior</h3><ul><li>Connection is returned after <strong>every</strong> SQL statement.</li><li>No BEGIN ... COMMIT. They will throw:</li></ul><p>ERROR: multi-statement transactions are disallowed in statement pooling mode</p><p><strong>Works only if:</strong></p><ul><li>One statement per request</li><li>No session state</li><li>No transactions</li></ul><p><strong>Example:</strong></p><p>SELECT value FROM config WHERE key = ‘feature_flag’;</p><h3>Spring Data JPA Note</h3><p>Even without @Transactional, Spring wraps read methods in a read-only transaction:</p><pre>@Repository<br>public interface BookRepository extends JpaRepository&lt;Book, Long&gt; {<br>    List&lt;Book&gt; findByAuthor(String author);<br>}<br><br>@Service<br>public class BookService {<br>    @Autowired<br>    BookRepository repo;<br><br>    public void listBooks() {<br>        List&lt;Book&gt; books = repo.findByAuthor(&quot;Jane Austen&quot;);<br>        books.forEach(System.out::println);<br>    }<br>}</pre><h3>PgBouncer Setup (Essentials)</h3><ul><li>Install on Linux: apt-get install pgbouncer or use Docker.</li><li>Edit pgbouncer.ini for DB and settings.</li><li>Run PgBouncer on a VM or container.</li><li>Change app DB URL:</li></ul><p>From: postgres://user:pass@dbhost:5432/mydb</p><p>To: postgres://user:pass@pgbouncer-host:6432/mydb</p><h3>Key Configuration Options</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*MOr-JHIcSzR2_BgvaEK1Yg.png" /></figure><h3>Sample pgbouncer.ini</h3><pre>[databases]<br>mydb = host=127.0.0.1 port=5432 dbname=mydb<br><br>[pgbouncer]<br>listen_addr = *<br>listen_port = 6432<br>auth_type = md5<br>auth_file = /etc/pgbouncer/userlist.txt<br>pool_mode = transaction<br>max_client_conn = 1000<br>default_pool_size = 20<br>server_reset_query = DISCARD ALL<br>logfile = /var/log/pgbouncer/pgbouncer.log<br>pidfile = /var/run/pgbouncer/pgbouncer.pid</pre><p><strong>Note:</strong> For Amazon RDS/Aurora, you can’t install PgBouncer on the DB. Run it in an EC2 or container in the same VPC. AWS RDS Proxy is an alternative, but PgBouncer is free.</p><h3>Real-World PgBouncer Performance Test</h3><p>I created a complete test setup that shows exactly how much PgBouncer improves database performance. Here’s what the test does:</p><h3>The Setup</h3><ul><li>AWS Infrastructure: Real PostgreSQL database + PgBouncer server + test client</li><li>Automated Scripts: Just run ./deploy.sh to create everything, ./post_deploy.sh to run tests</li><li>Fair Comparison: Same database, same queries, only connection method changes</li></ul><h3>3 Different Test Scenarios</h3><p>Test 1: Connection Overhead</p><ul><li>20 apps connecting to database, each makes 100 requests</li><li>Each request opens a new connection (worst case scenario)</li><li>Result: PgBouncer is 8x faster than direct connections</li></ul><p>Test 2: High Traffic</p><ul><li>80 apps connecting at the same time</li><li>Tests what happens when you approach database limits</li><li>Result: PgBouncer handles traffic much better</li></ul><p>Test 3: Extreme Load</p><ul><li>1000 apps trying to connect at once</li><li>Direct connections fail completely (database limit exceeded)</li><li>Result: PgBouncer still works, direct connections crash</li></ul><h3>What Gets Measured</h3><ul><li>Speed: How many requests per second</li><li>Response Time: How long each request takes</li><li>Reliability: How many requests succeed vs fail</li><li>Connection Rejections: How many connections get refused</li></ul><p>GitHub Repository: [<a href="https://github.com/ituitis-beydemir18/pgbouncer-performance-test"><em>https://github.com/ituitis-beydemir18/pgbouncer-performance-test</em></a>]</p><h3>PgBouncer Best Practices</h3><ul><li><strong>Use Transaction Pooling</strong>: Set pool_mode = transaction. Avoid session unless needed.</li><li><strong>Avoid Session Features</strong> in transaction mode:</li><li>SET, temp tables, advisory locks</li><li>Use SET LOCAL instead of SET</li><li><strong>Tune Pool Sizes</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*eIVIgqoSYJdbwY3fLnMFPA.png" /></figure><ul><li><strong>Keep App Pool Too</strong>: Don’t disable HikariCP or similar. Use small pools in both app and PgBouncer.</li><li><strong>Watch Timeouts</strong>: idle_timeout, query_timeout</li><li><strong>Enable Health Checks</strong>: Use pause_mode to survive DB restarts.</li><li><strong>Scale Horizontally</strong>: PgBouncer uses one CPU. Run multiple instances and load-balance if needed.</li><li><strong>Secure It</strong>: Use firewall/Security Group, Enable SSL if needed</li></ul><h3>Alternatives</h3><ul><li><strong>AWS RDS Proxy</strong> (Managed + failover)</li><li><strong>PgCat</strong> (Multi-host, multi-threading)</li><li><strong>PgPool-II</strong> (Read/write splitting)</li></ul><p>For simple pooling, PgBouncer remains the best starting choice.</p><h3>📚 References</h3><ul><li><a href="https://jpcamara.com/2023/04/12/pgbouncer-is-useful.html">https://jpcamara.com/2023/04/12/pgbouncer-is-useful.html</a></li><li><a href="https://engineering.teknasyon.com/pgbouncer-d%C3%BC%C5%9F%C3%BCk-kaynak-t%C3%BCketimli-postgresql-pool-">https://engineering.teknasyon.com/pgbouncer-d%C3%BC%C5%9F%C3%BCk-kaynak-t%C3%BCketimli-postgresql-pool</a>-y%C3%B6neticisi-4ebd94fcd45c?gi=39a2a5116543</li><li><a href="https://mesuutt.com/2018/03/pgbouncer/">https://mesuutt.com/2018/03/pgbouncer/</a></li><li><a href="https://devcenter.heroku.com/articles/best-practices-pgbouncer-configuration">https://devcenter.heroku.com/articles/best-practices-pgbouncer-configuration</a></li><li><a href="https://www.pgbouncer.org/faq.html">https://www.pgbouncer.org/faq.html</a></li><li><a href="https://cloudnative-pg.io/documentation/1.15/connection_pooling/">https://cloudnative-pg.io/documentation/1.15/connection_pooling/</a></li><li><a href="https://www.enterprisedb.com/postgres-tutorials/pgbouncer-setup-extended-architecture-use-cases-and-leveraging-">https://www.enterprisedb.com/postgres-tutorials/pgbouncer-setup-extended-architecture-use-cases-and-leveraging-</a>soreuseport</li><li><a href="https://dba.stackexchange.com/questions/274307/prepared-statements-with-pgbouncer">https://dba.stackexchange.com/questions/274307/prepared-statements-with-pgbouncer</a></li><li><a href="https://medium.com/hackernoon/understanding-postgres-connection-pooling-with-pgbouncer-unlisted-draft-bdb7ebf073ab">https://medium.com/hackernoon/understanding-postgres-connection-pooling-with-pgbouncer-unlisted-draft-bdb7ebf073ab</a></li><li><a href="https://www.architecture-weekly.com/p/architecture-weekly-189-mastering">https://www.architecture-weekly.com/p/architecture-weekly-189-mastering</a></li><li><a href="https://overcast.blog/connection-pooling-in-kubernetes-a-guide-625af713b0e4?gi=1677c2bc0882">https://overcast.blog/connection-pooling-in-kubernetes-a-guide-625af713b0e4?gi=1677c2bc0882</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec784dda605" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>