<?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 Mehmet AK on Medium]]></title>
        <description><![CDATA[Stories by Mehmet AK on Medium]]></description>
        <link>https://medium.com/@mehmet-ak?source=rss-74619620b34b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BoAFP0jTYjw25S6SA1uIEg.jpeg</url>
            <title>Stories by Mehmet AK on Medium</title>
            <link>https://medium.com/@mehmet-ak?source=rss-74619620b34b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:03:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehmet-ak/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[Terminalde AI Dönemi: GitHub Copilot CLI ile Akıllı Terminal]]></title>
            <link>https://medium.com/@mehmet-ak/terminalde-ai-d%C3%B6nemi-github-copilot-cli-ile-ak%C4%B1ll%C4%B1-terminal-bd1127d746b6?source=rss-74619620b34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd1127d746b6</guid>
            <category><![CDATA[co-pilot]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Mehmet AK]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 09:43:09 GMT</pubDate>
            <atom:updated>2026-03-16T09:43:09.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*ejlrBCQq_F4c0sQB28X03Q.png" /><figcaption>GitHub Copilot CLI</figcaption></figure><p>Terminal, bir yazılımcının en saf ve en güçlü aracıdır. Ancak bazen o güç, hatırlanması imkansız parametreler ve karmaşık “pipe” zincirleri arasında bir yük haline gelebilir. GitHub Copilot CLI, bu noktada devreye girerek terminali sadece komut koşturduğunuz bir siyah ekran olmaktan çıkarıp, sizinle konuşan ve iş akışınızı anlayan akıllı bir yardımcıya dönüştürüyor.</p><h3>GitHub Copilot CLI Nedir?</h3><p>GitHub Copilot CLI (Command Line Interface), GitHub Copilot’un yapay zeka yeteneklerini doğrudan terminalinize taşıyan bir araçtır. Geleneksel arama motorlarında “linux delete files older than 30 days” gibi aramalar yapmak yerine, doğrudan terminale ne yapmak istediğinizi doğal dille söylersiniz ve o size doğru komutu hazırlar.</p><h3>Öne Çıkan Özellikler</h3><p>GitHub Copilot kodlama aracının gücünü artık yerel ortamınızda ve senkronize bir şekilde deneyimleyebilirsiniz:</p><ul><li><strong>Terminal-Native Geliştirme:</strong> Kodlama asistanınızla doğrudan komut satırında çalışın; editör ve terminal arasında sürekli bağlam değiştirmek (context switching) zorunda kalmayın.</li><li><strong>Kutudan Çıktığı Gibi GitHub Entegrasyonu:</strong> Mevcut GitHub hesabınızla kimlik doğrulaması yaparak repolarınıza, issue’larınıza ve pull request’lerinize doğal dille erişin.</li><li><strong>Agentic (Aracı) Yetenekleri:</strong> Sadece komut önermekle kalmaz; karmaşık görevleri planlayabilen ve yürütebilen bir yapay zeka ortağıyla kod inşa edin, düzenleyin, hata ayıklayın ve refactor yapın.</li><li><strong>MCP Destekli Genişletilebilirlik:</strong> Varsayılan olarak GitHub’ın <strong>Model Context Protocol (MCP)</strong> sunucusuyla birlikte gelir. Kendi özel MCP sunucularınızı ekleyerek asistanınızın yeteneklerini projenize özel olarak genişletebilirsiniz.</li><li><strong>Tam Kontrol Sizde:</strong> Güvenlik ve doğruluk her şeydir. Asistanın önerdiği her eylemi yürütmeden önce önizleyebilir ve onaylayabilirsiniz; sizin açık onayınız olmadan hiçbir işlem gerçekleşmez.</li></ul><h3>🛠 Kurulum ve Yapılandırma</h3><p>GitHub Copilot CLI’yı sisteminize dahil etmek oldukça basittir. Ben kurulumu <strong>Node.js</strong> ve <strong>npm</strong> üzerinden gerçekleştirdim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*JCEY1LmCzOOp17Fu2FSJeA.png" /></figure><p>Yükleme tamamlandıktan sonra GitHub hesabınızla eşleştirme yapmanız gerekir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*y1q0Ov-_KKWP5IVLhQ9NsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCxkL0MQ9F2-5o5e_fiuww.png" /></figure><p>Ekranda çıkan kodu GitHub hesabınızla onaylayarak hesabınızı kolaylıkla eşleştirme yapabilirsiniz.</p><p><strong>Not:</strong> Ben npm yolunu tercih ettim ancak GitHub CLI (gh) üzerinden kurulum gibi diğer yöntemler için <a href="https://github.com/github/copilot-cli?tab=readme-ov-file">buradan </a>bilgi edinebilirsiniz.</p><h3>Birlikte Deneyelim: Copilot CLI Kullanım Modları ve Gerçek Örnekler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uqvUmILivPbiiGbGjyWEw.png" /></figure><p>İlk olarak terminalden github copilot’ı açtıktan sonra /model komutu ile çalışmak istediğimiz yapay zeka modelimizi seçiyoruz. Sonrasında ilk incelemek istediğimiz modu olan önerme moduyla örneklerimize başlayalım.</p><p><strong>Temel Kullanım Modları</strong></p><ul><li><strong>Komut Önerme (Suggest) — gh copilot suggest</strong></li></ul><p>Bu modda Copilot CLI, yazdığınız <strong>doğal dili</strong> analiz ederek ihtiyacınıza uygun terminal komutunu üretir. Komutları ezberlemeden, ne yapmak istediğinizi söylemeniz yeterlidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyCl2mj5KWy-oDDEQwO5nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eg0mmIKRXCSHGzrWlfco4w.png" /></figure><p><em>Eğer interaktif menülerle vakit kaybetmek istemiyorsanız, doğrudan </em><em>-p (prompt) parametresini kullanarak tek satırda işinizi halledebilirsiniz. Örneğin: </em><em>gh copilot suggest -p &quot;son 24 saatte değişen dosyaları listele&quot; Bu kullanım, terminal hızınıza hız katar.</em></p><ul><li><strong>Komut Açıklama (Explain) — gh copilot explain</strong></li></ul><p>Explain mode, karmaşık veya başkasından alınmış komutların ne yaptığını adım adım açıklar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZrSj5uX_CXfEnVJxWcPSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rbUwYS7AHR67ZttAC4YlQ.png" /></figure><ul><li><strong>Hatalı Komutları Düzeltme</strong></li></ul><p>Copilot CLI, hata aldığınız senaryoyu analiz eder ve çözüm önerir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnW3htNbvF-0-n7jdwRPRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjdxz0upvN-dt8Pquyc7Dg.png" /></figure><p><strong>GitHub Copilot CLI</strong>, terminali sadece komutların çalıştırıldığı statik bir alan olmaktan çıkarıp, yazılımcıyla işbirliği yapan dinamik bir <strong>yapay zeka ortağına</strong> dönüştürüyor. Karmaşık parametreleri ezberleme zorunluluğunu ortadan kaldıran bu araç; doğal dille komut üretme (<strong>suggest</strong>), karmaşık satırları analiz etme (<strong>explain</strong>) ve hataları anında onarma yetenekleriyle geliştirme sürecini ciddi ölçüde hızlandırıyor.</p><p><strong>Neden Kullanmalısınız?</strong></p><ul><li><strong>Odaklanma:</strong> Editör ve tarayıcı arasında kaybolmadan terminalde kalmanızı sağlar.</li><li><strong>Güvenlik:</strong> Her komutu yürütmeden önce onayınıza sunarak kontrolü size bırakır.</li><li><strong>Öğrenme:</strong> Sadece komutu vermekle kalmaz, mantığını açıklayarak terminal hakimiyetinizi artırır.</li></ul><p>Kısacası; Copilot CLI, terminalin gücünü yapay zekanın hızıyla birleştirerek modern yazılım geliştirme süreçlerinde yeni bir standart belirliyor. Artık “Bu komutun parametresi neydi?” diye düşünmek yerine, sadece <strong>ne yapmak istediğinize</strong> odaklanabilirsiniz.</p><p><strong>Otomasyon ve Verimlilik: CLI’ın Ötesi</strong></p><p><em>Copilot CLI sadece anlık sorularınız için değil, aynı zamanda tekrarlayan iş akışlarınızı otomatize etmek için de harika bir potansiyele sahip.</em></p><ul><li><strong>Süreç Entegrasyonu:</strong> Karmaşık CI/CD süreçlerinde veya yerel scriptlerinizde hatırlamakta zorlandığınız pipeline oluşturmak için Copilot’tan yardım alabilir, bu yapıları bash scriptlerinize entegre edebilirsiniz.</li><li><strong>Tekrarlayan Promptlar:</strong> Sıkça kullandığınız ama karmaşık olan sorguları bir alias haline getirerek, kendi özel “akıllı komut setinizi” oluşturabilirsiniz. Bu, terminali sadece kullanan değil, onu kendi ihtiyaçlarına göre programlayan bir geliştirici olmanızı sağlar.</li></ul><p><strong>Umarım bu bilgiler işinize yarar ve iş akışınızı kolaylaştırır. Okuduğunuz için teşekkürler.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd1127d746b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EF Core’da Transaction Yönetimi: Veri Tutarlılığının Kalbi]]></title>
            <link>https://medium.com/@mehmet-ak/ef-coreda-transaction-y%C3%B6netimi-veri-tutarl%C4%B1l%C4%B1%C4%9F%C4%B1n%C4%B1n-kalbi-3806a01f1283?source=rss-74619620b34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3806a01f1283</guid>
            <dc:creator><![CDATA[Mehmet AK]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 06:36:40 GMT</pubDate>
            <atom:updated>2026-02-03T06:36:40.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*-WO9oJEo3nZ69lesoSb1Yw.png" /></figure><p>Bugün Entity Framework Core’un en kritik konularından birine, Transaction Yönetimi’ne derinlemesine dalacağız. Bir fintech şirketinde çalıştığınızı, bir hastane bilgi sistemi geliştirdiğinizi ya da bir e-ticaret platformu yönettiğinizi düşünün. Bu sistemlerin ortak noktası ne? Veri tutarlılığı. İşte transaction’lar bu tutarlılığın sigortasıdır.</p><h3>Transaction Nedir? Neden Önemlidir?</h3><p>Transaction (işlem), veritabanında gerçekleştirilen bir dizi operasyonun <strong>atomik</strong> bir birim olarak ele alınmasıdır. Ya <strong>hepsi başarılı</strong> olur, ya da <strong>hiçbiri</strong> olmaz. Bu prensibi ACID özellikleriyle tanırız:</p><ul><li><strong>Atomicity (Atomiklik)</strong>: İşlemler bölünemez bir bütündür.</li><li><strong>Consistency (Tutarlılık)</strong>: Veriler her zaman geçerli durumda kalır.</li><li><strong>Isolation (İzolasyon)</strong>: Eş zamanlı işlemler birbirini etkilemez.</li><li><strong>Durability (Kalıcılık)</strong>: Tamamlanan işlemler kalıcıdır.</li></ul><p>Gerçek Hayattan Bir Örnek: E-Ticaret Siparişi :</p><p>Bir müşteri 500₺’lik bir ürün satın alıyor. Arka planda şu işlemler gerçekleşmeli:</p><ol><li><strong>Stoktan ürün düşülür</strong> (Products tablosu)</li><li><strong>Kullanıcının bakiyesi azalır</strong> (Users tablosu)</li><li><strong>Sipariş kaydı oluşturulur</strong> (Orders tablosu)</li><li><strong>Satıcıya bildirim gönderilir</strong> (Notifications tablosu)</li></ol><p><strong>Sorun</strong>: 2. adım başarılı oldu ama sunucu 3. adımda çöktü. Sonuç? Müşterinin parası çekildi ama siparişi yok!</p><p>İşte transaction bu durumu engeller. Herhangi bir adım başarısız olursa, <strong>tüm değişiklikler rollback ile geri alınır.</strong></p><h3><strong>EF Core’da Transaction Yönetimi Nasıl Çalışır?</strong></h3><ol><li><strong>Implicit (Örtük) Transaction: SaveChanges()</strong></li></ol><p>EF Core’da her SaveChanges() çağrısı otomatik olarak bir transaction başlatır. Bu, tek bir kaydetme işleminde birden fazla değişiklik yapıyorsanız yeterlidir.</p><pre>// Tek bir SaveChanges içinde tüm değişiklikler atomiktir<br>var product = await _context.Products.FindAsync(productId);<br>product.Stock -= 1;<br><br>var order = new Order <br>{ <br>    ProductId = productId, <br>    UserId = userId, <br>    Amount = 500 <br>};<br>_context.Orders.Add(order);<br><br>// Bu satır çalıştığında, hem Product hem Order <br>// tek bir transaction içinde güncellenir<br>await _context.SaveChangesAsync();</pre><p><strong>✅ Ne zaman kullanılır?</strong></p><ul><li>Tek bir SaveChanges() yeterli olduğunda</li><li>Basit CRUD işlemlerinde</li><li>İş mantığı karmaşık değilse</li></ul><p><strong>❌ Ne zaman yetmez?</strong></p><ul><li>Birden fazla SaveChanges() gerektiğinde</li><li>Harici API çağrıları veya dosya işlemleri arasında</li><li>Manuel rollback kontrolü gerektiğinde</li></ul><p><strong>İPUCU : </strong>Birçok senaryoda aşağıda bahsedeceğimBeginTransaction&#39;ı açmanıza gerek yoktur. Eğer tüm işlemleriniz aynı DbContext üzerindeyse ve veriler arasında navigation property tanımlıysa, nesneleri birbirine bağlayıp tek bir SaveChangesAsync() çağırmak en performanslı yöntemdir. Bu yöntem, veritabanı üzerindeki kilit süresini en aza indirir.</p><pre>public async Task CreateOrderEfficientlyAsync(int userId, List&lt;CartItem&gt; cartItems, CancellationToken cancellationToken= default)<br>{<br>    // 1. Ana nesneyi (User) ilişkili verileriyle birlikte çekiyoruz<br>    var user = await _context.Users<br>        .Include(u =&gt; u.Orders)<br>        .FirstOrDefaultAsync(u =&gt; u.Id == userId, cancellationToken);<br><br>    if (user == null) throw new Exception(&quot;Kullanıcı bulunamadı.&quot;);<br><br>    // 2. Yeni bir Sipariş nesnesi oluşturuyoruz<br>    var newOrder = new Order<br>    {<br>        OrderDate = DateTime.UtcNow,<br>        OrderItems = new List&lt;OrderItem&gt;()<br>    };<br><br>    foreach (var item in cartItems)<br>    {<br>        var product = await _context.Products.FindAsync(new object[] { item.ProductId }, ct);<br>        <br>        // Stok düşümü: Product nesnesindeki değişiklik EF tarafından izleniyor (tracking)<br>        product.Stock -= item.Quantity;<br><br>        // Sipariş kalemini listeye ekliyoruz (Navigation Property kullanımı)<br>        newOrder.OrderItems.Add(new OrderItem <br>        { <br>            ProductId = item.ProductId, <br>            Quantity = item.Quantity,<br>            UnitPrice = product.Price <br>        });<br>    }<br><br>    // 3. Siparişi kullanıcının sipariş listesine ekliyoruz<br>    user.Orders.Add(newOrder);<br><br>    // 4. TEK BİR ATOMİK İŞLEM:<br>    // EF Core burada otomatik olarak bir transaction başlatır.<br>    // Stok güncellemeleri, Order kaydı ve OrderItems kayıtlarının TAMAMI <br>    // başarılı olursa commit edilir, biri bile hata alsa hepsi geri alınır.<br>    await _context.SaveChangesAsync(cancellationToken);<br>}</pre><p>Neden Bu Yöntemi Tercih Etmelisiniz?</p><ul><li><strong>Veritabanı Round-trip Azalır:</strong> Birden fazla SaveChangesAsync yerine tek seferde tüm komutlar (INSERT ve UPDATE) gönderilir.</li><li><strong>Lock Süresi Kısalır:</strong> Transaction veritabanı seviyesinde sadece milisaniyeler sürer; kod tarafındaki try-catch blokları arasında açık kalmaz.</li><li><strong>Temiz Kod:</strong> BeginTransaction, Commit ve Rollback gibi kalabalık kod bloklarından kurtulursunuz.</li><li><strong>CancellationToken Desteği:</strong> Fark ettiyseniz tüm asenkron metodlarımıza cancellationToken parametresini geçtik. Uygulamalarda kullanıcı işlemi tamamlanmadan sayfayı kapatabilir. Eğer bu parametreyi kullanmazsak, veritabanı sunucusu &quot;hayalet bir işlem&quot; yürütmeye devam eder ve gereksiz yere satırları kilitli (lock) tutar. CancellationToken sayesinde, istek iptal edildiği an veritabanı operasyonu da durdurulur ve kaynaklar anında serbest bırakılır.</li></ul><p><strong>Manuel Transaction Yönetimi</strong></p><p>2. Explicit (Açık) Transaction: BeginTransaction</p><p>Karmaşık senaryolarda kontrolü tamamen elinize almanız gerekir.</p><pre>using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken);<br><br>    try<br>    {<br>        // Adım 1: Stok kontrolü ve güncelleme<br>        var product = await _context.Products<br>            .FirstOrDefaultAsync(p =&gt; p.Id == productId, cancellationToken);<br>        <br>        if (product == null || product.Stock &lt; 1)<br>            throw new InvalidOperationException(&quot;Ürün stokta yok!&quot;);<br>        <br>        product.Stock -= 1;<br>        await _context.SaveChangesAsync(cancellationToken);<br>        <br>        // Adım 2: Kullanıcı bakiyesi kontrolü<br>        var user = await _context.Users<br>            .FirstOrDefaultAsync(u =&gt; u.Id == userId, cancellationToken);<br>        <br>        if (user.Balance &lt; product.Price)<br>            throw new InvalidOperationException(&quot;Yetersiz bakiye!&quot;);<br>        <br>        user.Balance -= product.Price;<br>        await _context.SaveChangesAsync(cancellationToken);<br>        <br>        // Adım 3: Sipariş oluşturma<br>        var order = new Order { /* ... properties ... */ };<br>        _context.Orders.Add(order);<br>        await _context.SaveChangesAsync(cancellationToken);<br>        <br>        await transaction.CommitAsync(cancellationToken);<br>    }<br>    catch (Exception ex)<br>    {<br>        await transaction.RollbackAsync(cancellationToken);<br>        _logger.LogError(ex, &quot;İşlem sırasında hata oluştu, geri alınıyor.&quot;);<br>        throw;<br>    }</pre><h3><strong>Gerçek Hayat Problemleri ve Çözümleri</strong></h3><p>Şimdiye kadar EF Core’un bize sunduğu transaction araçlarını gördük. Ancak asıl kritik soru şu: <strong>Production ortamında hangi senaryolarla karşılaşırsınız ve bunları nasıl çözersiniz?</strong> Şimdi teoriden pratiğe geçelim ve gerçek dünya problemlerine somut çözümler getirelim.</p><p>Problem 1: Deadlock</p><p><strong>Senaryo</strong>: İki kullanıcı aynı anda farklı sırayla aynı kayıtları güncellemeye çalışıyor.</p><p>Transaction 1: Product A’yı kilitle → Product B’yi kilitle<br>Transaction 2: Product B’yi kilitle → Product A’yı kilitle</p><p>Sonuç? İkisi de birbirini bekler, sistem kilitlenir! 🔒</p><p>✅ Çözüm 1: Tutarlı Sıralama</p><pre>// ❌ YANLIŞ: Rastgele sıralama<br>await UpdateProduct(productB);<br>await UpdateProduct(productA);<br><br>// ✅ DOĞRU: Her zaman ID sırasına göre<br>var productIds = new[] { productA, productB }.OrderBy(x =&gt; x);<br>foreach (var id in productIds)<br>{<br>    await UpdateProduct(id);<br>}</pre><p>✅ Çözüm 2: Retry Logic ile Deadlock Yönetimi</p><pre>public async Task&lt;bool&gt; ExecuteWithDeadlockRetry(<br>    Func&lt;Task&gt; operation, <br>    int maxRetries = 3)<br>{<br>    int retryCount = 0;<br>    <br>    while (retryCount &lt; maxRetries)<br>    {<br>        try<br>        {<br>            await operation();<br>            return true;<br>        }<br>        catch (DbUpdateException ex) <br>            when (ex.InnerException?.Message.Contains(&quot;deadlock&quot;) == true)<br>        {<br>            retryCount++;<br>            <br>            if (retryCount &gt;= maxRetries)<br>            {<br>                _logger.LogError(<br>                    &quot;Deadlock {RetryCount} kez denendi, başarısız oldu.&quot;, <br>                    retryCount<br>                );<br>                throw;<br>            }<br>            <br>            // Exponential backoff: Her denemede bekleme süresi artar<br>            var delay = TimeSpan.FromMilliseconds(100 * Math.Pow(2, retryCount));<br>            <br>            _logger.LogWarning(<br>                &quot;Deadlock tespit edildi. {Delay}ms sonra yeniden denenecek. &quot; +<br>                &quot;Deneme: {RetryCount}/{MaxRetries}&quot;, <br>                delay.TotalMilliseconds, retryCount, maxRetries<br>            );<br>            <br>            await Task.Delay(delay);<br>        }<br>    }<br>    <br>    return false;<br>}<br><br>// Kullanımı<br>await ExecuteWithDeadlockRetry(async () =&gt;<br>{<br>    using var transaction = await _context.Database.BeginTransactionAsync();<br>    // İşlemleriniz...<br>    await transaction.CommitAsync();<br>});</pre><p>Problem 2: Dirty Reads ve Phantom Reads</p><p><strong>Senaryo</strong>: Bir transaction henüz commit edilmemiş veriyi okuyor veya başka bir transaction yeni satırlar ekliyor.</p><h4>✅ Çözüm: Isolation Level Ayarı</h4><p>EF Core’da 4 ana izolasyon seviyesi vardır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*1SRmRe9RNpnTOCVURkGYLg.png" /><figcaption>Isolation Level</figcaption></figure><pre>// Finansal raporlama: En güvenli seviye<br>using var transaction = await _context.Database<br>    .BeginTransactionAsync(IsolationLevel.Serializable);<br><br>try<br>{<br>    var totalRevenue = await _context.Orders<br>        .Where(o =&gt; o.Status == OrderStatus.Completed)<br>        .SumAsync(o =&gt; o.Amount);<br>    <br>    var report = new FinancialReport<br>    {<br>        Period = &quot;Q1-2026&quot;,<br>        TotalRevenue = totalRevenue,<br>        GeneratedAt = DateTime.UtcNow<br>    };<br>    <br>    _context.Reports.Add(report);<br>    await _context.SaveChangesAsync();<br>    await transaction.CommitAsync();<br>}<br>catch<br>{<br>    await transaction.RollbackAsync();<br>    throw;<br>}</pre><p>Snapshot Isolation: Okuma Yoğun Sistemler İçin İdeal</p><pre>// SQL Server&#39;da Snapshot özelliğini aktifleştirin:<br>// ALTER DATABASE YourDatabase SET ALLOW_SNAPSHOT_ISOLATION ON;<br><br>using var transaction = await _context.Database<br>    .BeginTransactionAsync(IsolationLevel.Snapshot);<br><br>// Artık okuma işlemleri yazma işlemlerini bloklamaz<br>// Versiyon tabanlı sistem kullanılır</pre><p><strong>Ne zaman Snapshot kullanmalı?</strong></p><ul><li>E-ticaret ürün listeleme sayfaları</li><li>Raporlama ve analytics</li><li>Okuma/yazma oranı 80/20 veya daha fazla olan sistemler</li></ul><p>Problem 3: Connection Resiliency (Bağlantı Hataları)</p><p><strong>Senaryo</strong>: Azure SQL veya bulut veritabanında geçici ağ kopması yaşanıyor.</p><h4>✅ Çözüm: Execution Strategy ile Retry Mekanizması</h4><pre>// Startup.cs veya Program.cs içinde<br>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        connectionString,<br>        sqlOptions =&gt; sqlOptions<br>            .EnableRetryOnFailure(<br>                maxRetryCount: 5,<br>                maxRetryDelay: TimeSpan.FromSeconds(30),<br>                errorNumbersToAdd: null<br>            )<br>    )<br>);</pre><p><strong>⚠️ DİKKAT</strong>: Retry stratejisi varsa, BeginTransaction doğrudan kullanılamaz!</p><pre>// ❌ YANLIŞ: Retry stratejisi ile çalışmaz<br>using var transaction = await _context.Database.BeginTransactionAsync();<br><br>// ✅ DOĞRU: ExecutionStrategy kullanın<br>var strategy = _context.Database.CreateExecutionStrategy();<br><br>await strategy.ExecuteAsync(async () =&gt;<br>{<br>    using var transaction = await _context.Database.BeginTransactionAsync();<br>    <br>    try<br>    {<br>        // İş mantığınız<br>        var order = new Order { /* ... */ };<br>        _context.Orders.Add(order);<br>        await _context.SaveChangesAsync();<br>        <br>        // Harici bir API çağrısı<br>        await _paymentService.ProcessPaymentAsync(order.Id);<br>        <br>        await transaction.CommitAsync();<br>    }<br>    catch<br>    {<br>        await transaction.RollbackAsync();<br>        throw; // Strategy için throw şart!<br>    }<br>});</pre><p>Problem 4: Long-Running Transactions (Uzun Süren İşlemler)</p><p><strong>Senaryo</strong>: Transaction açık kaldığı süre boyunca ilgili satırlar kilitli kalır. Bu da sistemde tıkanıklığa yol açar.</p><p>✅ Çözüm: Transaction Süresini Minimize Edin</p><pre>// ❌ YANLIŞ: Transaction içinde ağır işlemler<br>using var transaction = await _context.Database.BeginTransactionAsync();<br><br>var orders = await _context.Orders.ToListAsync();<br><br>// Transaction açıkken 10 saniye süren bir işlem<br>foreach (var order in orders)<br>{<br>    await _externalApiService.SendNotificationAsync(order); // YAVAŞ!<br>}<br><br>await transaction.CommitAsync();<br><br>// ✅ DOĞRU: Transaction dışında ağır işlemleri yapın<br>var orders = await _context.Orders.ToListAsync();<br><br>// Önce harici işlemleri tamamlayın<br>var notifications = new List&lt;NotificationResult&gt;();<br>foreach (var order in orders)<br>{<br>    notifications.Add(<br>        await _externalApiService.SendNotificationAsync(order)<br>    );<br>}<br><br>// Sonra hızlı bir transaction açın<br>using var transaction = await _context.Database.BeginTransactionAsync();<br><br>foreach (var notification in notifications)<br>{<br>    var log = new NotificationLog<br>    {<br>        OrderId = notification.OrderId,<br>        Status = notification.Status<br>    };<br>    _context.NotificationLogs.Add(log);<br>}<br><br>await _context.SaveChangesAsync();<br>await transaction.CommitAsync(); // Çok hızlı!</pre><p>4 temel problemi ve çözümlerini ele aldık. Ancak bu çözümlerin <strong>çalıştığını nasıl doğrularsınız? </strong>Bir hata oluştuğunda <strong>kök nedeni nasıl bulursunuz?</strong> Production ortamında transaction hatalarını anlamak için <strong>kapsamlı loglama</strong> ve <strong>monitoring</strong> şarttır. Şimdi EF Core’un interceptor mekanizmasını kullanarak nasıl profesyonel bir izleme sistemi kuracağımızı görelim.</p><h3>Transaction Logging ve İzlenebilirlik</h3><p>Production ortamında transaction hatalarını anlamak çok önemlidir.</p><p>Custom Transaction Interceptor</p><pre>public class TransactionLoggingInterceptor : DbTransactionInterceptor<br>{<br>    private readonly ILogger&lt;TransactionLoggingInterceptor&gt; _logger;<br><br>    public TransactionLoggingInterceptor(<br>        ILogger&lt;TransactionLoggingInterceptor&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    public override InterceptionResult&lt;DbTransaction&gt; TransactionStarting(<br>        DbConnection connection,<br>        TransactionStartingEventData eventData,<br>        InterceptionResult&lt;DbTransaction&gt; result)<br>    {<br>        _logger.LogInformation(<br>            &quot;Transaction başlatılıyor. IsolationLevel: {IsolationLevel}, &quot; +<br>            &quot;ConnectionId: {ConnectionId}&quot;,<br>            eventData.IsolationLevel,<br>            eventData.ConnectionId<br>        );<br><br>        return base.TransactionStarting(connection, eventData, result);<br>    }<br><br>    public override void TransactionCommitted(<br>        DbTransaction transaction,<br>        TransactionEndEventData eventData)<br>    {<br>        _logger.LogInformation(<br>            &quot;Transaction başarıyla commit edildi. &quot; +<br>            &quot;TransactionId: {TransactionId}, Süre: {Duration}ms&quot;,<br>            transaction.TransactionId,<br>            eventData.Duration.TotalMilliseconds<br>        );<br><br>        base.TransactionCommitted(transaction, eventData);<br>    }<br><br>    public override void TransactionRolledBack(<br>        DbTransaction transaction,<br>        TransactionEndEventData eventData)<br>    {<br>        _logger.LogWarning(<br>            &quot;Transaction rollback yapıldı! &quot; +<br>            &quot;TransactionId: {TransactionId}, Süre: {Duration}ms&quot;,<br>            transaction.TransactionId,<br>            eventData.Duration.TotalMilliseconds<br>        );<br><br>        base.TransactionRolledBack(transaction, eventData);<br>    }<br>}<br><br>// Startup.cs içinde kaydedin<br>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options<br>        .UseSqlServer(connectionString)<br>        .AddInterceptors(new TransactionLoggingInterceptor(logger))<br>);</pre><h3>Cross-Context Transactions</h3><p><strong>Senaryo</strong>: Farklı veritabanları veya context’ler arasında tutarlılık gerekiyor.</p><pre>public class OrderService<br>{<br>    private readonly OrderDbContext _orderContext;<br>    private readonly InventoryDbContext _inventoryContext;<br><br>    public async Task CreateOrderAsync(CreateOrderRequest request)<br>    {<br>        // Aynı connection string kullanıyorlarsa<br>        using var transaction = await _orderContext.Database<br>            .BeginTransactionAsync();<br><br>        try<br>        {<br>            // İlk context&#39;te işlemler<br>            var order = new Order { /* ... */ };<br>            _orderContext.Orders.Add(order);<br>            await _orderContext.SaveChangesAsync();<br><br>            // İkinci context&#39;i aynı transaction&#39;a bağla<br>            await _inventoryContext.Database.UseTransactionAsync(<br>                transaction.GetDbTransaction()<br>            );<br><br>            // İkinci context&#39;te işlemler<br>            var inventory = await _inventoryContext.Products<br>                .FindAsync(request.ProductId);<br>            inventory.Stock -= request.Quantity;<br>            await _inventoryContext.SaveChangesAsync();<br><br>            // Her iki context de başarılı, commit<br>            await transaction.CommitAsync();<br>        }<br>        catch<br>        {<br>            await transaction.RollbackAsync();<br>            throw;<br>        }<br>    }<br>}</pre><p>Transaction yönetimi bir <strong>mühendislik dengesi</strong> gerektiriyor: Tutarlılık mı, performans mı? Manuel kontrol mü, implicit transaction mı? Serializable mı, Snapshot mı? Aşağıdaki tablo, bu kararları vermenize yardımcı olacak bir <strong>cheat sheet</strong> niteliğinde.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*xxiSBRZn_wi5r_rvBYnEOQ.png" /><figcaption>Best Practices</figcaption></figure><p>Transaction yönetimi, yazılım geliştirmede görünmez kahramandır. Kullanıcılar bunu fark etmez ama olmazsa sistem çöker. Bu yazıda öğrendiklerimizi özetleyelim:</p><ul><li><strong>Transaction ne zaman gerekli</strong>: Birden fazla işlem atomik olmalıysa</li><li><strong>Deadlock nasıl önlenir</strong>: Tutarlı sıralama + Retry logic</li><li><strong>Isolation Level nasıl seçilir</strong>: İş gereksinimlerine göre</li><li><strong>Bulut ortamlarında ne yapılır</strong>: ExecutionStrategy ile resiliency</li><li><strong>Nasıl debug edilir</strong>: Custom interceptor ile loglama</li></ul><p><strong>Hatırlamanız gereken 3 altın kural:</strong></p><ol><li><strong>Transaction sürelerini kısa tutun</strong> — Her saniye kilitleme demektir</li><li><strong>Her zaman loglayın</strong> — Görünmeyen hata çözülemez</li><li><strong>Production için plan B hazırlayın</strong> — Retry, fallback, monitoring</li></ol><p>Bu yazıdaki örnekler, best practice’ler ve teknik detaylar aşağıdaki kaynaklardan derlenmiştir:</p><p><a href="https://learn.microsoft.com/en-us/ef/core/saving/transactions"><strong>Using Transactions — EF Core | Microsoft Learn</strong></a></p><p><a href="https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency"><strong>Connection Resiliency — EF Core | Microsoft Learn</strong></a></p><p><a href="https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/"><strong>DbContext Lifetime, Configuration, and Initialization | Microsoft Learn</strong></a></p><p><a href="https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql"><strong>SQL Server Transaction Isolation Levels | Microsoft Learn</strong></a></p><p><a href="https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors"><strong>Interceptors — EF Core | Microsoft Learn</strong></a></p><p>Bu yazıyı hazırlarken gerçek dünya deneyimlerinden ve production ortamında karşılaşılan problemlerden yola çıktım. Umarım sizin projelerinizde de faydalı olur.</p><p><strong>Sorularınız mı var?</strong> Yorumlarda buluşalım! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3806a01f1283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Data Consistency in Microservices: A Practical Approach with Event-Driven Architecture]]></title>
            <link>https://medium.com/@mehmet-ak/managing-data-consistency-in-microservices-a-practical-approach-with-event-driven-architecture-1dcc6a76b890?source=rss-74619620b34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dcc6a76b890</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[data-consistency]]></category>
            <dc:creator><![CDATA[Mehmet AK]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 11:30:19 GMT</pubDate>
            <atom:updated>2025-07-27T11:59:51.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*lTB1noFJIK70SFWk.jpg" /></figure><p>Today, we’re diving into a crucial topic for anyone working with microservices: <strong>managing data consistency across different services</strong>. In a microservice architecture, each service operates independently, owning its own data. This design offers immense benefits like independent development and deployment, but it also raises a key question: How do services access data owned by others without creating tight dependencies?</p><p>We’ll explore two main approaches to inter-service communication: <strong>synchronous</strong> and <strong>asynchronous</strong>. While synchronous communication is straightforward, it comes with limitations like tight coupling and potential for cascading failures. Our focus today will be on <strong>asynchronous communication</strong>, specifically using an <strong>event-driven architecture</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*X8c0WXslV8UW_W8V.png" /><figcaption>Event-Driven Architecture</figcaption></figure><p>We’ll delve into practical strategies, including how we utilize <strong>read-only meta tables</strong> with <strong>SQL triggers</strong> to keep data synchronized, and how we implement robust <strong>event publishing and consuming</strong> using <strong>MassTransit</strong> and <strong>RabbitMQ</strong> in .NET projects. Finally, we’ll discuss important considerations and potential challenges you might face when adopting this powerful architectural pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7YDs7LD5mmn7LutTmmJmQ.png" /><figcaption>Keeping data consistent across microservices is challenging but crucial. Here are 10 effective methods:</figcaption></figure><p>Choose the method that best fits your system’s needs, considering setup complexity, scalability, and consistency requirements.</p><h3>How to Access Data from Other Services in a Microservice Architecture?</h3><p>In a microservice architecture, each service operates within its own <strong>bounded context</strong> and is the sole owner of the data belonging to that domain. This means:</p><ul><li>Each service has its own database.</li><li>How data is accessed and updated is entirely under that service’s control.</li><li>Other services cannot access this data directly; they can only do so through defined interfaces (API, event, etc.).</li></ul><p>This structure allows:</p><ul><li>Services to be developed and deployed independently.</li><li>Changes in one service do not directly affect other services.</li><li>The system becomes more flexible, scalable, and easier to maintain.</li></ul><p>However, this service independence brings an important question when other services occasionally need access to certain data: “How do we manage this data sharing?” At this point, two fundamental approaches emerge: synchronous and asynchronous communication. In this article, we will detail how we manage data consistency, especially with asynchronous communication, using an event-driven architecture, and how we build a structure through meta tables and libraries (e.g., MassTransit, RabbitMQ).</p><h3><strong>🔗 Synchronous Communication</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*kfffl5EJAhdWQmV06_-_MQ.png" /><figcaption>(Synchronous Communication)</figcaption></figure><p>One of the most direct and common ways to share data between microservices is through synchronous communication. In this model, a service instantly retrieves the data it needs from another service. Communication is typically established via HTTP using protocols like REST API or gRPC. The calling service pauses its operation and waits until it receives a response.</p><p>This structure is quite simple and easy for developers to understand. By directly calling the information needed from another service, the operation is completed instantly. This method is particularly functional in scenarios that involve direct user interaction, such as user login or form submission, where an immediate response is required.</p><p>However, this simplicity also carries some risks. In synchronous communication, the calling service is directly dependent on the availability of the other service. This means the operation cannot proceed without a response. This is a significant point of failure for system resilience.</p><p>For example, if the service providing the data is inaccessible — which can frequently occur due to network outages, service crashes, or temporary slowdowns — the calling service also begins to wait, times out, or throws an error. Thus, a minor glitch can lead to <strong>cascading failures</strong> throughout the system.</p><p>This structure also creates a <strong>tight coupling</strong> between services. When one service changes, the likelihood of other services using it being affected increases. This weakens the core promise of microservice architecture: “independent development and deployment.”</p><p>Synchronous communication may suffice for small and stable structures. However, as the number of services and traffic increases, the complexity of the system also rises proportionally. This brings performance issues and makes system scalability difficult.</p><p>In conclusion, while synchronous communication offers simple, understandable, and fast solutions, it can be limited in scenarios where the system requires high availability, <strong>loose coupling</strong>, and fault tolerance. At this point, approaches like asynchronous communication and event-driven architecture offer much more suitable, sustainable, and flexible solutions for microservice architecture. Now, let’s examine the advantages of these alternative structures and how they are implemented.</p><h3><strong>📨 Asynchronous Communication</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*zDfYKtcRsk4qRCNUYkdP9A.png" /><figcaption>(Asynchronous Communication)</figcaption></figure><p>To reduce risks such as dependency, performance bottlenecks, and error chains caused by synchronous communication, asynchronous communication is widely preferred in the microservice world. In this model, services communicate with each other via messages without being directly dependent. When a service wants to send data to another service, it says “I have completed this operation” and publishes this information as a message (<strong>event</strong>). Other services listen for this message and take action according to their needs.</p><p>This communication style is typically carried out via a <strong>message broker</strong> (e.g., RabbitMQ, Kafka) or an event streaming platform. Services no longer need each other to be live and accessible. The sent message is stored in the queue, and the receiving service retrieves and processes the message when it is available.</p><p>This model mostly works with a “<strong>fire-and-forget</strong>” approach. That is, the sending service does not wait or query whether the message has been delivered or processed. After delivering the message to the queue system, it continues its own operation. This makes the system faster and more flexible.</p><p>⚙️ How It Works?</p><ul><li><strong>Producer (Publishing Service):</strong> After an operation is performed, it sends the relevant information as an event to a queue system (e.g., RabbitMQ).</li><li><strong>Message Broker (Message Queue):</strong> Stores the event and guarantees its delivery to the relevant listener service(s).</li><li><strong>Consumer (Listening Service):</strong> Receives this event and performs the relevant action (update, save, trigger, etc.) according to its needs.</li></ul><p>The strongest aspect of this structure is that it makes the system <strong>loosely coupled</strong>. This means services can be unaware of each other’s status but still work together harmoniously.</p><p>🧠 Why Asynchronous?</p><ul><li><strong>Independence:</strong> If one service is down, the entire system does not crash. The message waits in the queue and is processed when the service is back up.</li><li><strong>Scalability:</strong> Under load, messages pushed to the queue can be processed sequentially; sudden spikes in traffic do not affect the entire system.</li><li><strong>Performance:</strong> The processing service continues its work without waiting for the other side to process. This reduces delays in the system.</li><li><strong>Fire-and-Forget:</strong> The sending service continues its operation without waiting for the delivery result.</li><li><strong>Loose Coupling:</strong> When one service changes, it does not directly affect other services. This means easier versioning, testing, and deployment.</li></ul><p>CAP Theorem &amp; Trade-Offs:<br>In event-driven architectures, we inherently accept *eventual consistency* as per the CAP theorem’s constraints:<br>- Consistency (C): Sacrificed momentarily during event propagation<br>- Availability (A): Prioritized (services remain operational)<br>- Partition Tolerance (P): Guaranteed (via message brokers)</p><p>This conscious trade-off ensures system resilience while typically maintaining sub-second data consistency.</p><p>🛠️ Example Application</p><p>In the model we use in an example microservice project, we can clearly separate the read and write paths of the data and manage it as follows:</p><p>📖 1. Read-Only Meta Tables</p><p>Each microservice is the sole owner of the data within its domain and writes to this data only itself. However, it is quite common for different services to need a portion of this data for read purposes.</p><p>In such scenarios, instead of requiring other services to connect directly to the database or make synchronous API calls, we copy only the read-only part of the data to their own systems via <strong>read-only meta tables</strong>.</p><p>The main features of these tables are:</p><ul><li>They contain only specific columns of the actual database (e.g., ID, Name-Surname, Status, etc.).</li><li>They are strictly used for read-only purposes; no writing is performed.</li><li>They are synchronized with changes from the source.</li></ul><p>Each service only reads data from its own meta table; the actual writing operation is done only in the main service.</p><p>🧩 Keeping Meta Tables Up-to-Date: SQL Triggers</p><p>To ensure data changes are immediately reflected in meta tables, we define separate triggers for INSERT, UPDATE, and DELETE operations in the relevant source service database. These triggers ensure that data remains consistent across multiple subsystems.</p><p>⚠️ Note on Trigger Limitations:<br>While triggers provide a simple way to sync meta tables, they create tight coupling between databases and don’t handle distributed transactions well. For production systems at scale, consider:</p><ul><li>Transactional Outbox Pattern (atomic event publishing)</li><li>Change Data Capture (CDC) tools like Debezium</li></ul><p>These alternatives better maintain service independence while ensuring data consistency.</p><p>Below is an example trigger structure. This structure ensures that when a record is added, it is automatically copied to meta tables:</p><p>✅ <strong>Insert Trigger — Update Meta Table on New Book Addition</strong></p><pre>CREATE TRIGGER trg_Books_Insert<br>ON EducationServiceDB.dbo.Books<br>AFTER INSERT<br>AS<br>BEGIN<br>    SET NOCOUNT ON;<br><br>    INSERT INTO LibraryService_MetaDB.dbo.Books (BookId, Title, Author, PublishedYear, CreatedDate)<br>    SELECT BookId, Title, Author, PublishedYear, CreatedDate FROM inserted;<br>END;</pre><p>🔄 <strong>Update Trigger — Synchronize Meta Table When Book Information is Updated</strong></p><pre>CREATE TRIGGER trg_Books_Update<br>ON EducationServiceDB.dbo.Books<br>AFTER UPDATE<br>AS<br>BEGIN<br>    UPDATE meta<br>    SET <br>        meta.Title = i.Title,<br>        meta.Author = i.Author,<br>        meta.PublishedYear = i.PublishedYear,<br>        meta.ModifiedDate = i.ModifiedDate<br>    FROM LibraryService_MetaDB.dbo.Books meta<br>    JOIN inserted i ON meta.BookId = i.BookId;<br>END;</pre><p>❌ <strong>Delete Trigger — Delete from Meta Table if Book is Deleted</strong></p><pre>CREATE TRIGGER trg_Books_Delete<br>ON EducationServiceDB.dbo.Books<br>AFTER DELETE<br>AS<br>BEGIN<br>    DELETE FROM LibraryService_MetaDB.dbo.Books<br>    WHERE BookId IN (SELECT BookId FROM deleted);<br>END;</pre><p>Thanks to this structure, while EducationService owns its Books data, LibraryService can only use this data read-only through its meta table. Thus, there is no need to make synchronous API calls to pull data from other services, establishing a performant and secure structure.</p><p>📬 2. Sending and Consuming Events (MassTransit + RabbitMQ)</p><p>To ensure data consistency between microservices and maintain the principle of <strong>loose coupling</strong>, communicating data changes in the system via events is one of the most common and effective methods. In this method, when a change occurs in one service, this event is shared asynchronously with other relevant services.</p><p>We build this structure in our .NET projects using <strong>MassTransit</strong> and <strong>RabbitMQ</strong>.</p><p>MassTransit provides a very lean, extensible, and robust structure for event publish/consume operations in the .NET ecosystem. RabbitMQ, on the other hand, acts as a broker in this messaging process, ensuring that messages are transported securely, sequentially, and scalably.</p><h3>Event bus implementation with RabbitMQ</h3><p>⚙️ Implementation Steps</p><p>🔸 <strong>1. Event Publish (Producer)</strong></p><p>The service managing the data (e.g., UserService), creates and publishes an event representing this change when an update occurs:</p><pre>// UserService - Publisher<br>await _publishEndpoint.Publish(new UserUpdatedEvent {<br>    UserId = user.Id,<br>    FullName = user.FullName,<br>    Email = user.Email,<br>    UpdatedAt = DateTime.UtcNow<br>});<br>//This event carries the information &quot;user information changed&quot; in the system and is transmitted to the RabbitMQ queue.</pre><p>🔸 <strong>2. Event Consume (Consumer)</strong></p><p>Other relevant services (e.g., OrderService, NotificationService) listen for this event and update their meta tables when they capture it:</p><pre>// OrderService - Consumer<br>public class UserUpdatedConsumer : IConsumer&lt;UserUpdatedEvent&gt;<br>{<br>    public async Task Consume(ConsumeContext&lt;UserUpdatedEvent&gt; context)<br>    {<br>        var user = context.Message;<br><br>        // Update the User record in the meta table<br>        var existingUser = await _userMetaRepository.GetByIdAsync(user.UserId);<br>        if (existingUser != null)<br>        {<br>                            existingUser.FullName = user.FullName;<br>                            existingUser.Email = user.Email;<br>                            existingUser.UpdatedAt = user.UpdatedAt;<br><br>            await _userMetaRepository.UpdateAsync(existingUser);<br>        }<br>    }<br>}<br>//Thanks to this structure, OrderService does not depend on UserService&#39;s API or database. Each service keeps its own copy updated.</pre><p>✅ <strong>Advantages Provided by This Structure</strong></p><ul><li><strong>No inter-service dependency:</strong> Even if one service is down, others continue to operate.</li><li><strong>Near real-time data flow is provided:</strong> Events are processed quickly.</li><li><strong>Performance increases:</strong> Read operations are separate, write operations are separate. API calls are reduced.</li><li><strong>Load balancing is easier:</strong> RabbitMQ processes messages sequentially and controllably.</li><li><strong>Versioning and independent deployment are easier:</strong> New services can be brought online simply by subscribing to the relevant event.</li><li><strong>Back-pressure can be managed:</strong> In situations of heavy traffic, messages are queued and processed sequentially.</li></ul><p>⚠️ <strong>Points to Consider and Potential Challenges</strong></p><p>As with any powerful architectural approach, event-driven systems require careful planning and implementation. To maintain the flexibility and performance advantages this structure brings, there are some important points and potential challenges to keep in mind:</p><p>🔁 1. Event Inconsistencies (Out-of-Sync Data)</p><p>Meta tables are updated as events are processed, which means data may be updated with a few seconds of delay rather than instantly. If an event is lost or not processed correctly on the consumer side, this can lead to data inconsistencies. Therefore, writing <strong>idempotent consumers</strong> that produce the same result even if an event arrives multiple times is critically important.</p><p>🔄 2. Event Loss / Delivery Guarantees</p><p>Messaging systems like RabbitMQ typically offer an “<strong>at-least-once delivery</strong>” guarantee. This means an event can be delivered more than once but will not be lost. However, in situations such as network issues, consumer errors, or system outages, messages can get stuck in the queue, not be processed, or enter an infinite retry loop, leading to unexpected behavior.</p><p>❗ <strong>Recommendation:</strong> Actively configure <strong>retry policies</strong>, <strong>dead-letter queues</strong>, and comprehensive <strong>error handling</strong> strategies with libraries like MassTransit. This significantly increases your system’s resilience.</p><p>🧱 3. Structure and Limitations of Meta Tables</p><p>Meta tables should contain only minimal, read-only data. They should never be used as the primary data source; they should only hold essential fields that your application depends on (ID, Name-Surname, Status, etc.). Since performance losses can occur as meta tables grow, be careful to only keep fields that are useful for your work.</p><p>🔂 4. Evolution of Event Schemas</p><p>Microservices evolve over time, and naturally, event schemas can also expand. It is vital that existing older consumers do not break when new fields are added to an event.</p><p>❗ <strong>Recommendation:</strong> Implement <strong>event versioning</strong> (e.g., UserUpdatedV1, UserUpdatedV2). This approach allows new consumers to transition to the new version while old consumers continue to work seamlessly with existing event schemas.</p><p>🚦 5. Comparison with Trigger-Based Method</p><p>Database triggers for meta table updates can offer a quick solution for simple scenarios. However, when advanced needs such as scalability, event log tracking, and comprehensive retry mechanisms are concerned, an event-driven structure is much more flexible. Copying operations done with triggers can directly burden the database and do not offer the ability to log events in detail.</p><p>🔍 Monitoring &amp; Observability Essentials:<br>- Distributed Tracing: Implement correlation IDs (OpenTelemetry/Jaeger) to track event flows<br>- Event Auditing: Log events to Elasticsearch/Seq for debugging and replay<br>- Metrics: Monitor RabbitMQ queue lengths and processing times (Prometheus/Grafana)</p><p>🚀 Conclusion</p><p>An event-driven architecture built with MassTransit and RabbitMQ is a powerful way to both ensure data consistency between microservices and increase system flexibility. However, for this structure to be sustainable:</p><ul><li>Events must be well-designed and clearly defined.</li><li>Consumers must be developed to be <strong>idempotent</strong>.</li><li>Comprehensive <strong>monitoring</strong> and <strong>alerting</strong> systems must be active.</li><li>Data inconsistency scenarios must be considered in advance, and mitigation strategies developed.</li></ul><p>Remember: Event-driven architecture derives its power from independence and flexibility. However, without a robust infrastructure, a disciplined approach, and proactive solutions to potential challenges, this structure can become complex and chaotic over time. With the right steps, you can unleash the true potential of your microservices.</p><p>I hope I have addressed the points of interest and provided sufficient explanations on the subject. Thank you for taking your valuable time to read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dcc6a76b890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Redis ile Caching Dünyasına Giriş — Neden, Nasıl ve Ne Zaman?]]></title>
            <link>https://medium.com/@mehmet-ak/redis-ile-caching-d%C3%BCnyas%C4%B1na-giri%C5%9F-neden-nas%C4%B1l-ve-ne-zaman-4a9e436c588e?source=rss-74619620b34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a9e436c588e</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Mehmet AK]]></dc:creator>
            <pubDate>Wed, 28 May 2025 07:53:39 GMT</pubDate>
            <atom:updated>2025-05-28T07:53:39.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Redis ile Caching Dünyasına Giriş — Neden, Nasıl ve Ne Zaman?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvbSTmcbM3dSJ5kpunxRtA.png" /></figure><p>Bugün Medium’da ilk yazımı paylaşmanın mutluluğunu yaşıyorum. Sizlerle, geçtiğimiz aylarda stajyerlik döneminde sunumunu yaptığım ve her geliştiricinin mutlaka bilmesi gereken bir konuyu, <strong>Caching ve Redis’i</strong> derinlemesine konuşmak istiyorum. Eğer API’larınızın yavaşlığından şikayetçiyseniz veya sistem performansını nasıl artıracağınızı merak ediyorsanız birlikte bu konuya bir bakış atmakta fayda var. Redis ve cache bilgileri doğrultusunda günün sonunda motivasyonumuz “Say Goodbye to Slow APIs 🖐️ ” olacaktır.</p><h3>🧠 Caching Nedir?</h3><p>En basit haliyle, <strong>cache</strong>, sık erişilen verilerin geçici olarak saklandığı hızlı bir bellek alanıdır. Asıl amacı;<br>✅ Sistem performansını artırmak<br>✅ Veri erişim süresini kısaltmak<br>✅ Uygulama yanıt süresini iyileştirmek</p><p>Örneğin, bir kullanıcı sürekli aynı ürünleri görüntülüyorsa, bu ürünleri her seferinde veritabanından çekmek yerine, RAM üzerinde saklamak hem zaman kazandırır hem de sunucu yükünü azaltır. Örneğin bir e-ticaret uygulaması düşün, kullanıcı her ürün detayına bastığında tekrar tekrar veritabanına gitmek çok maliyetli olur. Bu verileri bir defa belleğe alıp oradan hızlıca sunmak daha iyi olacaktır.</p><h3>Cache Türleri: In-Memory vs. Distributed Caching 🤯</h3><p>Cache kavramını anladığımıza göre, şimdi iki ana türüne göz atalım:</p><ol><li><strong>In-Memory Cache:</strong> Adından da anlaşılacağı gibi, verileri uygulamanın çalıştığı sunucunun RAM’inde (belleğinde) saklar. Bu sayede verilere doğrudan bellekten okunduğu için işlem süresi çok azdır ve yüksek performanslı çalışır. Ancak dikkat, uygulamanız yeniden başlatıldığında veya sunucu çöktüğünde bu veriler kaybolur. Ayrıca, tek bir sunucu üzerinde çalıştığınız durumlar için idealdir.</li><li><strong>Distributed Caching:</strong> Bu tür, verileri birden fazla sunucuda dağıtarak depolar. Veriler birden fazla sunucuda tutulduğu için sistemin yükü dağıtılır ve veriye erişim daha hızlı hale gelir. Büyük ölçekli, yüksek trafikli uygulamalar için vazgeçilmezdir çünkü tek bir hata noktasını ortadan kaldırır ve ölçeklenebilirlik sağlar.</li></ol><h3>🧬 Caching Stratejileri: On-Demand vs Prepopulation</h3><p>Cache’in ne zaman ve nasıl doldurulacağı da önemli. İki ana stratejiden bahsedelim:</p><pre>| Özellik             | On-Demand                                  | Prepopulation                              |<br>|---------------------|--------------------------------------------|--------------------------------------------|<br>| **Veri Yükleme**    | Talep edildiğinde yüklenir                | Uygulama başlatıldığında yüklenir          |<br>| **Performans**      | İlk erişimde yavaş olabilir               | Hızlı başlangıç sağlar                     |<br>| **Veri Güncelliği** | Dinamik veriler için uygundur             | Sabit veriler için kullanılır              |<br>| **Bellek Kullanımı**| Daha verimli (ihtiyaç anında yükler)      | Daha fazla (önceden yüklenir)              |<br>| **Örnek**           | Spotify şarkıyı ilk açtığınızda cache&#39;ler | Redis&#39;te popüler veriler önceden yüklenir  |</pre><p>Spotify’da bir şarkıyı ilk dinlediğinizde cache’e alınması “On-Demand” stratejisine güzel bir örnekken, uygulamanız başladığında sık kullanılan bir ürün listesini Redis’e yüklemek “Prepopulation” stratejisine örnek olabilir.</p><h3>🚀 Redis Nedir?</h3><p>Redis, RAM üzerinde çalışan, açık kaynak kodlu, key-value tabanlı bir <strong>veri deposu</strong>dur.<br>İlk bakışta bir <strong>cache aracı</strong> gibi görünse de aslında Redis çok daha fazlasını sunar.<br>Yani sadece “verileri geçici tutan” bir sistem değil; karmaşık, yüksek trafikli, gerçek zamanlı uygulamalarda <strong>kritik bir rol oynayabilecek kadar güçlü</strong> bir altyapıdır.</p><h3>Peki Redis sadece bir cache mi? Hayır! Redis, düşündüğünüzden çok daha fazlası:</h3><h4>🔧 Gerçek bir veritabanıdır</h4><p>Evet, yanlış duymadınız. Redis, verilerin sadece geçici olarak saklandığı bir cache katmanı değil, <strong>kalıcı olarak</strong> da saklanabildiği bir veritabanıdır.</p><h4>💾 Birden fazla kalıcılık (persistence) mekanizması sunar</h4><ul><li><strong>RDB (Snapshotting):</strong> Belirli aralıklarla disk’e snapshot alır.</li><li><strong>AOF (Append Only File):</strong> Her yazma işlemi diske kaydedilir.</li><li>Her iki yöntemi bir arada kullanmak da mümkündür!</li></ul><h4>⚡ Süper hızlıdır</h4><p>RAM üzerinde çalıştığı için veriye erişim süresi <strong>milisaniyeler seviyesindedir.</strong><br>Ağ gecikmesi, disk IO gibi yavaşlatıcı etkenler ortadan kalkar.</p><h4>🧩 Esnek veri yapıları sunar</h4><p>Sadece string değil, aşağıdaki gibi farklı yapı türlerini de destekler:</p><ul><li>String, List, Set, Sorted Set, Hash, Bitmap, Geo gibi daha az bilinen türler</li></ul><h4>🌍 Yerleşik birincil-çoğaltma (master-slave) mimarisi vardır</h4><p>Yüksek erişilebilirlik ve veri çoğaltması için bir Redis örneği “master”, diğerleri “slave” olarak yapılandırılabilir.<br>Slave’ler yalnızca okuma, master hem okuma hem yazma yapar.</p><h4>🧪 Açık kaynaklı ve sürekli gelişen bir projedir</h4><p>Redis topluluğu çok aktiftir. Her geçen gün yeni özellikler, modüller ve iyileştirmelerle büyür.</p><h4>🔐 Transaction desteği sunar</h4><p>MULTI, EXEC, WATCH gibi komutlarla atomik işlemler yapılabilir.<br>Bu sayede Redis sadece hızlı değil, aynı zamanda <strong>güvenlidir</strong>.</p><h4>📬 Mesaj kuyruğu olarak da kullanılabilir</h4><p>Redis’in <strong>Pub/Sub (Publisher / Subscriber)</strong> özelliği sayesinde servisler arasında mesajlaşma senaryoları da rahatlıkla uygulanabilir.</p><h4>☕ Spring ve popüler framework’lerle uyumludur</h4><p>Java dünyasında Spring (Jedis, Lettuce), .NET’te StackExchange.Redis, Python’da redis-py, Node.js’te node_redis, Ruby’de redis-rb, PHP’de phpredis, C/C++’ta hiredis ve cpp_redis, Swift’te RediStack gibi popüler kütüphaneler Redis’i doğrudan destekler.</p><h4>🧩 Modüler yapısıyla genişletilebilir</h4><p>RediSearch, RedisJSON, RedisGraph gibi modüllerle Redis’in işlevselliğini artırmak mümkündür.<br>Yani Redis’i sadece bir key-value store olmaktan çıkarıp neredeyse <strong>çok yönlü bir NoSQL veritabanına </strong>dönüştürebilirsiniz.</p><h3>⚠️ CAP Teoremi &amp; Redis</h3><p>CAP Teoremi, dağıtık sistemlerin aynı anda üç özelliği sağlayamayacağını söyler:<br><strong>Consistency (Tutarlılık), Availability (Erişilebilirlik), Partition Tolerance (Bölünme Toleransı)</strong></p><p>Redis bu üçlüyü şöyle dengeler:</p><ul><li>✅ <strong>Partition Tolerance</strong>: Redis Cluster yapısı ile veriyi dağıtarak bölünmeye karşı dayanıklıdır.</li><li>✅ <strong>Availability</strong>: Master-slave yapısı ile yüksek erişilebilirlik sunar.</li><li>⚠️ <strong>Consistency</strong>: Anlık tutarsızlıklar (replikasyon gecikmesi) yaşanabilir.</li></ul><p>Bu nedenle Redis’i kullanırken kullanım senaryosuna göre öncelik belirlemek çok önemlidir.</p><h3>Redis Nerede Kullanılır?</h3><pre>| Senaryo      | Açıklama                                                                 |<br>|--------------|--------------------------------------------------------------------------|<br>| 🎧 Spotify    | İlk kez dinlenen şarkılar cache&#39;lenir                                   |<br>| 🚗 Uber       | Araç konumu ve sürücü eşleşmesi gerçek zamanlı işlenir                  |<br>| 🧰 GitHub     | İş kuyrukları Redis üzerinden asenkron yönetilir                       |<br>| 📱 Instagram  | Anlık içerik sunumu ve kişiselleştirme Redis ile yapılır                |</pre><h3>🧑‍💻 Kodla Pratik: Redis ile Catalog Cache Uygulaması</h3><p>Kod örnekleriyle Redis’i nasıl kullanacağımıza yukarıda da bahsettiğim gibi, .NET Core üzerinde Redis ile caching ve dağıtık kilit mekanizmalarını inceleyeceğiz.</p><h4>Redis Servisi: Temel İşlemler</h4><p>Öncelikle, Redis ile etkileşim kuracak temel bir servis oluşturalım. RedisService.cs dosyamız şöyle görünecek:</p><pre>using System;<br>using System.Text.Json;<br>using StackExchange.Redis;<br><br>namespace Catolog.Api.Services;<br><br>public class RedisService<br>{<br>    private readonly IConnectionMultiplexer _redis;<br>    private readonly IDatabase _db;<br><br>    public RedisService(string connectionString)<br>    {<br>        // Redis bağlantısını başlatıyoruz<br>        _redis = ConnectionMultiplexer.Connect(connectionString);<br>        // Varsayılan veritabanını alıyoruz<br>        _db = _redis.GetDatabase();<br>    }<br><br>    // Veriyi Redis&#39;e yazma metodu (generik tip T ile esneklik sağlıyoruz)<br>    public async Task SetAsync&lt;T&gt;(string key, T value)<br>    {<br>        // Nesneyi JSON&#39;a serileştiriyoruz<br>        var json = JsonSerializer.Serialize(value);<br>        await _db.StringSetAsync(key, json);<br>    }<br><br>    // Veriyi Redis&#39;ten okuma metodu<br>    public async Task&lt;T&gt; GetAsync&lt;T&gt;(string key)<br>    {<br>        // JSON olarak okuduğumuz veriyi tekrar nesneye dönüştürüyoruz<br>        var json = await _db.StringGetAsync(key);<br>        return json.HasValue ? JsonSerializer.Deserialize&lt;T&gt;(json) : default;<br>    }<br><br>    // Belirli bir anahtardaki veriyi Redis&#39;ten silme metodu<br>    public async Task RemoveAsync(string key)<br>    {<br>        await _db.KeyDeleteAsync(key);<br>    }<br>}</pre><p>Burada StackExchange.Redis kütüphanesini kullanıyoruz. SetAsync ile herhangi bir .NET objesini JSON&#39;a çevirip Redis&#39;e kaydedebiliyoruz. GetAsync ile de bu JSON veriyi tekrar istediğimiz objeye dönüştürebiliyoruz. RemoveAsync ise cache&#39;deki bir veriyi silebiliyoruz.</p><h4>Catalog Servisi: Caching’i Uygulamak</h4><p>Şimdi de CatalogService.cs dosyamıza bakalım ve yukarıdaki RedisService&#39;i nasıl kullanacağımızı görelim. Bu servis, ürün katalog bilgilerini yönetiyor ve Redis&#39;i kullanarak veritabanı yükünü azaltmayı hedefliyor.</p><pre>using System;<br>using Catolog.Api.Model;<br>using Catolog.Api.Repositories;<br><br>namespace Catolog.Api.Services;<br><br>public class CatalogService<br>{<br>    private readonly CatalogRepository _repository;<br>    private readonly RedisService _redisService;<br>    private const string CacheKeyPrefix = &quot;Catalog_&quot;; // Cache anahtarlarımız için bir önek<br><br>    public CatalogService(CatalogRepository repository, RedisService redisService)<br>    {<br>        _repository = repository;<br>        _redisService = redisService;<br>    }<br><br>    // Tüm katalogları getirme metodu<br>    public async Task&lt;IEnumerable&lt;Catalog&gt;&gt; GetAllAsync()<br>    {<br>        var cacheKey = $&quot;{CacheKeyPrefix}All&quot;; // Tüm kataloglar için cache anahtarı<br><br>        // Önce cache&#39;e bakıyoruz<br>        var cachedCatalogs = await _redisService.GetAsync&lt;IEnumerable&lt;Catalog&gt;&gt;(cacheKey);<br><br>        if (cachedCatalogs != null)<br>        {<br>            Console.WriteLine(&quot;Veri Cache&#39;ten geldi!&quot;);<br>            return cachedCatalogs; // Cache&#39;te varsa direkt döndürüyoruz<br>        }<br><br>        // Cache&#39;te yoksa veritabanından alıyoruz<br>        var catalogs = _repository.GetAll();<br>        // Aldığımız veriyi cache&#39;e yazıyoruz<br>        await _redisService.SetAsync(cacheKey, catalogs);<br>        Console.WriteLine(&quot;Veri Veritabanından geldi ve Cache&#39;e yazıldı!&quot;);<br>        return catalogs;<br>    }<br><br>    // ID&#39;ye göre katalog getirme metodu<br>    public async Task&lt;Catalog&gt; GetByIdAsync(int id)<br>    {<br>        var cacheKey = $&quot;{CacheKeyPrefix}{id}&quot;; // Belirli bir ID için cache anahtarı<br><br>        // Önce cache&#39;e bakıyoruz<br>        var cachedCatalog = await _redisService.GetAsync&lt;Catalog&gt;(cacheKey);<br><br>        if (cachedCatalog != null)<br>        {<br>            Console.WriteLine($&quot;ID: {id} için veri Cache&#39;ten geldi!&quot;);<br>            return cachedCatalog; // Cache&#39;te varsa direkt döndürüyoruz<br>        }<br><br>        // Cache&#39;te yoksa veritabanından alıyoruz<br>        var catalog = _repository.GetById(id);<br>        if (catalog != null)<br>        {<br>            // Aldığımız veriyi cache&#39;e yazıyoruz<br>            await _redisService.SetAsync(cacheKey, catalog);<br>            Console.WriteLine($&quot;ID: {id} için veri Veritabanından geldi ve Cache&#39;e yazıldı!&quot;);<br>        }<br>        return catalog;<br>    }<br>}</pre><p>Bu kodda, GetAllAsync ve GetByIdAsync metotlarında şöyle bir mantık izliyoruz:</p><ol><li>Öncelikle istenen verinin cache’te olup olmadığını kontrol ediyoruz.</li><li>Eğer veri cache’te varsa, direkt oradan çekip dönüyoruz, böylece veritabanına gitmek zorunda kalmıyoruz. Bu, yanıt süremizi inanılmaz kısaltıyor!</li><li>Eğer veri cache’te yoksa, veritabanına gidip veriyi çekiyoruz.</li><li>Veriyi çektikten sonra, bir sonraki istek için cache’e kaydediyoruz. Bu sayede aynı veri bir daha istendiğinde hızlıca cache’ten dönecek.</li></ol><p>Bu sayede API’larınızda “Say Goodbye to Slow APIs” mottomuzu gerçekleştirebiliyoruz.</p><h4>Dağıtık Kilit (Distributed Lock) ile Yarış Durumlarını Önleme 🔒</h4><p>Dağıtık sistemlerde, aynı anda birden fazla işlemin aynı kaynak üzerinde çalışmaya çalışması “yarış durumu” (race condition) denilen problemlere yol açabilir ve bu da veri tutarsızlığına neden olabilir. İşte burada dağıtık kilit (distributed lock) mekanizması devreye giriyor. Bir anda sadece bir işlemin kaynağı kullanmasını sağlayarak bu tür hataları önlüyor.</p><p>Redis, geçici anahtar-değer çiftlerini tutabilme yeteneği sayesinde harika bir dağıtık kilit yöneticisi olarak kullanılabilir. RedisLockService.cs örneğine bakalım:</p><pre>using StackExchange.Redis;<br><br>namespace StockService.Services<br>{<br>    // RedisLockService: Redis kullanarak birden fazla işlem arasında kilit (lock) yönetimi sağlar.<br>    public class RedisLockService<br>    {<br>        private readonly IDatabase _database;<br><br>        // Redis bağlantısını alır ve veritabanına bağlanır.<br>        public RedisLockService(IConnectionMultiplexer redis)<br>        {<br>            _database = redis.GetDatabase();<br>        }<br><br>        // AcquireLockAsync metodu, belirtilen anahtar (key) için bir kilit almaya çalışır.<br>        // Eğer kilit alınamazsa, false döner. Kilit alındığında true döner.<br>        // Kilit, belirtilen sürede (expiry) geçerli olur.<br>        public async Task&lt;bool&gt; AcquireLockAsync(string key, TimeSpan expiry)<br>        {<br>            // LockTakeAsync ile kilidi almaya çalışıyoruz. <br>            // Environment.MachineName: Kilidi alan istemcinin kimliği.<br>            return await _database.LockTakeAsync(key, Environment.MachineName, expiry);<br>        }<br><br>        // ReleaseLockAsync metodu, belirtilen anahtar için alınan kilidi serbest bırakır.<br>        // Kilit serbest bırakıldığında true döner.<br>        public async Task&lt;bool&gt; ReleaseLockAsync(string key)<br>        {<br>            // LockReleaseAsync ile kilidi serbest bırakıyoruz.<br>            return await _database.LockReleaseAsync(key, Environment.MachineName);<br>        }<br><br>        // Kilidi periyodik olarak yeniler. Bu yöntem, kilidin süresi bitmeden önce yenilenmesini sağlar.<br>        // CancellationToken ile iptal edilebilir.<br>        // Kilit, süreyi yarıya bölüp periyodik olarak yenilenir.<br>        public async Task RenewLockAsync(string key, TimeSpan expiry, CancellationToken cancellationToken)<br>        {<br>            while (!cancellationToken.IsCancellationRequested)<br>            {<br>                // Kilidi yenilemek için expiry süresinin yarısında bekler<br>                await Task.Delay(expiry / 2); // Expiry süresinin yarısında kilidi yenile<br><br>                // Kilidi uzatır<br>                await _database.LockExtendAsync(key, Environment.MachineName, expiry);<br>            }<br>        }<br>    }<br>}</pre><p>Bu serviste AcquireLockAsync metodu, LockTakeAsync komutunu kullanarak belirli bir anahtar için bir kilit almaya çalışıyor. Eğer kilit alınırsa true, alınamazsa false döner. Kilidin bir expiry süresi vardır, yani belirli bir süre sonra otomatik olarak serbest kalır. ReleaseLockAsync ise alınan kilidi serbest bırakmak için kullanılır. RenewLockAsync ise, kilidin süresi bitmeden önce onu sürekli olarak yenilemek için tasarlanmıştır, bu da uzun süren işlemler için kilidin kaybolmasını engeller.</p><p>Bu tarz bir dağıtık kilit uygulaması, özellikle <strong>Redlock Algoritması</strong>’nın temel prensiplerini içerir. Redlock, tek bir Redis instance’ına bağımlılığı ortadan kaldırarak yüksek erişilebilirlik gerektiren ortamlarda daha güvenilir bir dağıtık kilit mekanizması sağlar.</p><p>İlgili kod bloklarına ek olarak alttaki bilgiler de zaman zaman kullanışlı olmaktadır. Yazımı tamamlamadan önce burada bulunan ek bilgilere de göz atmakta fayda olacaktır.</p><h3>🧶 Redis Pipelining Nedir?</h3><p>Pipelining, çok sayıda komutu tek tek göndermek yerine bir arada Redis’e iletmemizi sağlar.<br>Bu da network üzerinden geçen <strong>RTT</strong> (Round Trip Time)’ı azaltır.</p><p>📌 Ne zaman kullanılır?</p><ul><li>Büyük verilerin batch olarak Redis’e yazılması/çekilmesi durumlarında</li><li>Örneğin 100 ürün bilgisini tek seferde cache’lemek gibi senaryolarda</li></ul><h3>🔐 Redis Transaction (MULTI-EXEC)</h3><p>Redis’te işlemleri bir bütün olarak yapmak için MULTI ve EXEC komutlarını kullanırız.<br>Yani ya hepsi çalışır ya da hiçbiri çalışmaz (atomiklik)</p><pre>MULTI<br>SET product_1 &quot;Bardak&quot;<br>SET product_2 &quot;Tabak&quot;<br>EXEC</pre><p>Ayrıca WATCH komutu ile bir anahtar izlenebilir. Eğer başka biri bu anahtarı değiştirirse, işlem iptal olur.</p><h3>⚠️ Dikkat Edilmesi Gerekenler</h3><p>Redis kullanırken şunlara dikkat:</p><p>❌ Her şeyi cache’leme!<br>✅ Expiration süresi koy.<br>✅ Preload yapılacak veriler sabit olmalı.<br>❌ Büyük JSON nesnelerini tümüyle yazma, gerekirse parçalara ayır.<br>✅ Memory limit belirle, overflow kontrolü yap.</p><h3>Daha fazlası için şu kaynaklara göz atabilirsiniz:</h3><ul><li><a href="https://redis.io/docs/"><strong>Redis Resmi Dokümantasyonu</strong></a></li><li><a href="https://github.com/StackExchange/StackExchange.Redis"><strong>StackExchange.Redis GitHub Sayfası</strong></a></li><li><a href="https://learn.microsoft.com/tr-tr/aspnet/core/performance/caching/distributed?view=aspnetcore-8.0"><strong>Microsoft Belgeleri — ASP.NET Core’da Dağıtılmış Önbellek</strong></a></li><li><a href="https://learn.microsoft.com/tr-tr/dotnet/core/extensions/caching"><strong>Microsoft Belgeleri — IDistributedCache Kullanımı</strong></a></li><li><a href="https://stackexchange.github.io/StackExchange.Redis/"><strong>StackExchange.Redis Kullanımı Örnekleri</strong></a></li><li><a href="https://developer.redis.com/develop/dotnet/"><strong>RedisLabs — .NET için Redis Quick Start Rehberi</strong></a></li><li><a href="https://redis.com/blog/"><strong>Redis Patterns ve En İyi Uygulamalar</strong></a></li></ul><p>Meslek hayatımın ilk yılında bu keyifli yazıyı sizlerle paylaşmanın mutluluğunu ve medium platformundaki ilk yazım olmasının heyecanını yaşıyorum. Umarım konu hakkında merak edilen noktalara değinmiş ve yeterli açıklamarda bulunabilmişimdir. Değerli zamanınızı ayırıp okuduğunuz için teşekkür ediyorum. Hepinize sağlıklı günler diliyorum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a9e436c588e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>