<?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 Ahmet DELLAL on Medium]]></title>
        <description><![CDATA[Stories by Ahmet DELLAL on Medium]]></description>
        <link>https://medium.com/@cedellalahmet?source=rss-8ef3c3229866------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*MbI2v-x79J3b7P_cCNLjHA.jpeg</url>
            <title>Stories by Ahmet DELLAL on Medium</title>
            <link>https://medium.com/@cedellalahmet?source=rss-8ef3c3229866------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:53:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cedellalahmet/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[Abstraction, Modularity, and Cognitive Complexity: Managing Software Systems]]></title>
            <link>https://cedellalahmet.medium.com/abstraction-modularity-and-cognitive-complexity-managing-software-systems-1a55d4957f8a?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a55d4957f8a</guid>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 09:46:08 GMT</pubDate>
            <atom:updated>2025-01-23T09:46:08.170Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing software systems, managing complexity can become a major challenge. The human brain struggles to keep track of numerous entities and their relationships, which is why we rely on <strong>abstraction</strong> and <strong>modularization</strong> to reduce the cognitive load. In this article, we’ll explore how to manage software system complexity using these tools, illustrated with Java code examples.</p><h3>Concepts and Complexity</h3><p>Every software system is composed of concepts — abstract representations that define the relationships between different parts of the system. For example, in a phonebook application, we might define concepts like first names, last names, numbers, sorting, and searching. These concepts can either be high-level or low-level, and the more concepts we have, the more complex the system becomes. However, with proper abstraction and modularization, we can manage this complexity effectively.</p><h4>Managing Complexity through Abstraction</h4><p>One way to introduce abstraction in Java is by using <strong>interfaces</strong> and <strong>abstract classes</strong>. These allow us to hide the implementation details and focus on what a component is supposed to do, rather than how it does it.</p><p><strong>Example 1: Abstraction and Interface Usage</strong></p><p>Let’s take the phonebook example again. We might have multiple ways of sorting the contact list, but each sorting method should follow the same interface so that other parts of the application remain independent of the sorting logic.</p><pre>// Interface for sorting names<br>public interface NameSorter {<br>    List&lt;Contact&gt; sort(List&lt;Contact&gt; contacts);<br>}<br>// Sorting by alphabetical order<br>public class AlphabeticalSorter implements NameSorter {<br>    @Override<br>    public List&lt;Contact&gt; sort(List&lt;Contact&gt; contacts) {<br>        contacts.sort(Comparator.comparing(Contact::getName));<br>        return contacts;<br>    }<br>}<br>// Sorting with locale-aware comparison<br>public class LocaleAwareSorter implements NameSorter {<br>    private Locale locale;<br>    public LocaleAwareSorter(Locale locale) {<br>        this.locale = locale;<br>    }<br>    @Override<br>    public List&lt;Contact&gt; sort(List&lt;Contact&gt; contacts) {<br>        Collator collator = Collator.getInstance(locale);<br>        contacts.sort((c1, c2) -&gt; collator.compare(c1.getName(), c2.getName()));<br>        return contacts;<br>    }<br>}</pre><p>In the example above, we’ve abstracted the sorting logic into the NameSorter interface, and multiple sorting strategies implement this interface. This helps <strong>reduce coupling</strong> between the phonebook and sorting logic, and makes it easier to add new sorting algorithms in the future without changing the core phonebook functionality.</p><h3>Using Modularity to Reduce Complexity</h3><p>A software system can be simplified by breaking it into modules, each handling a specific responsibility. Modularity helps by separating concerns and reducing the cognitive load of understanding the entire system at once.</p><p>When we divide our code into modules, we should aim for <strong>low coupling</strong> (minimal dependencies between modules) and <strong>high cohesion</strong> (related concepts are grouped together). In this way, each module becomes easier to maintain, test, and extend.</p><p>Let’s consider modularizing a phonebook system:</p><p><strong>Example 2: Modularity and Abstraction</strong></p><p>Let’s create a ContactManager class that deals with the business logic of the phonebook, while another class handles data access (e.g., fetching contacts from a database or file system).</p><pre>// Data Access Module: Abstracts database or file system operations<br>public class DataAccess {<br>    public List&lt;Contact&gt; fetchContacts() {<br>        // Fetch contacts from database or file<br>        return new ArrayList&lt;&gt;();<br>    }<br>}<br>// Business Logic Module: Manages contact-related operations<br>public class ContactManager {<br>    private DataAccess dataAccess;<br>    public ContactManager(DataAccess dataAccess) {<br>        this.dataAccess = dataAccess;<br>    }<br>    public void addContact(Contact contact) {<br>        List&lt;Contact&gt; contacts = dataAccess.fetchContacts();<br>        contacts.add(contact);<br>        // Save to database or file<br>    }<br>    public List&lt;Contact&gt; searchContacts(String query) {<br>        List&lt;Contact&gt; contacts = dataAccess.fetchContacts();<br>        return contacts.stream()<br>                       .filter(contact -&gt; contact.getName().contains(query))<br>                       .collect(Collectors.toList());<br>    }<br>}</pre><p>In this example, the ContactManager class is focused solely on business logic (adding and searching contacts), while the DataAccess class handles data retrieval. By splitting responsibilities into different modules, we make the system easier to maintain and extend.</p><h3>Reducing Coupling and Increasing Cohesion</h3><p>To reduce coupling, a module should only interact with its internal components. Any external dependencies should be isolated, and the module should expose a simple API to interact with the outside world.</p><p><strong>Example 3: Low Coupling and High Cohesion</strong></p><p>The ContactManager class could handle sorting and searching of contacts, but it should not directly deal with external dependencies like sorting algorithms. Instead, it should rely on an external sorter, which can be injected.</p><pre>// ContactManager module only focuses on its own logic<br>public class ContactManager {<br>    private List&lt;Contact&gt; contacts;<br>public ContactManager(List&lt;Contact&gt; contacts) {<br>        this.contacts = contacts;<br>    }<br>    // High cohesion: Sorting is handled by a separate module<br>    public List&lt;Contact&gt; sortContacts(NameSorter sorter) {<br>        return sorter.sort(contacts);<br>    }<br>    public List&lt;Contact&gt; searchContacts(String query) {<br>        return contacts.stream()<br>                       .filter(contact -&gt; contact.getName().contains(query))<br>                       .collect(Collectors.toList());<br>    }<br>}</pre><p>Here, the ContactManager class does not need to know how sorting is implemented; it simply delegates the sorting to a NameSorter instance. This maintains <strong>low coupling</strong> and <strong>high cohesion</strong> because the sorting logic is isolated in a separate module.</p><h3>Module Composition and Encapsulation</h3><p>Sometimes, composing modules can help create higher-level functionality. However, when modules are composed, we must ensure that they are not tightly coupled, as this can reduce flexibility and make the system harder to maintain.</p><p>In certain cases, you may need to encapsulate an internal module to reduce the external complexity, but this may also make it harder to reuse the module across different parts of the system.</p><p><strong>Example 4: Module Composition</strong></p><p>In our phonebook system, let’s say we want to create a new class that combines contact management with locale-aware sorting. This class will encapsulate the sorting logic and reduce the complexity of dealing with it externally.</p><pre>public class LocaleAwareContactManager {<br>    private List&lt;Contact&gt; contacts;<br>    private LocaleAwareSorter sorter;<br>public LocaleAwareContactManager(List&lt;Contact&gt; contacts, Locale locale) {<br>        this.contacts = contacts;<br>        this.sorter = new LocaleAwareSorter(locale);<br>    }<br>    public List&lt;Contact&gt; sortContacts() {<br>        return sorter.sort(contacts);<br>    }<br>}</pre><p>In this example, LocaleAwareContactManager uses the LocaleAwareSorter internally to provide locale-specific sorting. This reduces the external complexity for users of LocaleAwareContactManager, as they don&#39;t need to understand how sorting works internally.</p><h3>Conclusion: Managing Complexity with Abstraction and Modularity</h3><p>When developing software systems, <strong>abstraction</strong> and <strong>modularization</strong> are key strategies for managing complexity. By using <strong>abstraction</strong> to hide implementation details and <strong>modularization</strong> to break the system into smaller, more manageable parts, we can create software that is easier to maintain, extend, and test.</p><p>The Java examples provided throughout this article illustrate how abstraction and modularization can help achieve <strong>low coupling</strong> and <strong>high cohesion</strong>, which are fundamental principles of software design. By carefully organizing our code into modules with clear responsibilities, we can reduce the cognitive load on developers and make the system more adaptable to future changes.</p><p>By following these principles, we can not only simplify the development process but also ensure that our software systems remain sustainable and flexible as they grow.</p><p><em>This chapter is loosely based on </em><a href="https://blog.pragmaticengineer.com/a-philosophy-of-software-design-review/"><em>A Philosophy of Software Design</em></a><em> by </em>John Ousterhout.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a55d4957f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transactional Outbox Pattern.]]></title>
            <link>https://cedellalahmet.medium.com/transactional-outbox-pattern-148aa1063958?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/148aa1063958</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 23:27:09 GMT</pubDate>
            <atom:updated>2025-01-07T23:27:09.727Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Transactional Outbox</strong>, dağıtık sistemlerde ve mikroservis mimarilerinde veri tutarlılığını sağlamak için kullanılan bir desendir. Bu desen, veritabanı işlemleri ve mesajlaşma sistemleri arasında olabilecek tutarsızlıkları önler. Özellikle mikroservislerin birbirleriyle iletişim kurarken mesajlaşma (örn. RabbitMQ, Kafka) sistemleri kullandığı durumlarda kritik öneme sahiptir.</p><p>Normalde, veritabanı işlemleri ve mesaj iletimi birbirinden bağımsızdır, bu da veri tutarsızlığına yol açabilir. <strong>Transactional Outbox</strong>, her iki işlemi bir arada gerçekleştirir. Yani, bir veritabanı işlemi yapılırken, bu işlemle ilişkili mesajlar bir “outbox” tablosuna kaydedilir. Ardından, bu mesajlar asenkron bir şekilde dış bir servis tarafından kuyruklara iletilir.</p><h3>Temel Çalışma Prensibi</h3><ol><li><strong>Veritabanı Güncellemesi ve Mesajın Kaydedilmesi</strong>:</li></ol><ul><li>Bir işlem başlatıldığında (örneğin bir sipariş oluşturulduğunda), bu işlemle ilişkili bir mesaj aynı zamanda veritabanındaki bir outbox tablosuna kaydedilir. Böylece, veritabanı işlemi ve mesaj iletme işlemi bir <strong>transaction</strong> içerisinde gerçekleşir.</li></ul><ol><li><strong>Outbox’dan Mesajların Kuyruğa Gönderilmesi</strong>:</li></ol><ul><li>Arka planda çalışan bir servis, periyodik olarak outbox tablosunu kontrol eder ve PENDING durumundaki mesajları alarak, bunları ilgili mesaj kuyruğuna (örneğin RabbitMQ, Kafka) gönderir.</li></ul><ol><li><strong>Başarılı Gönderim Sonrası Güncelleme</strong>:</li></ol><ul><li>Mesaj başarıyla kuyruğa iletildiyse, mesajın durumu SENT olarak güncellenir. Eğer mesaj iletimi başarısız olursa, mesajın durumu FAILED olarak işaretlenir.</li></ul><p>Bu desen, veritabanı ve mesaj sistemleri arasındaki tutarsızlıkları engeller ve sistemin tutarlı bir şekilde çalışmasını sağlar.</p><h3>Java ile Transactional Outbox Uygulaması</h3><p>Şimdi, <strong>Transactional Outbox</strong> desenini bir Java Spring Boot uygulaması ile nasıl implement edebileceğimizi adım adım görelim.</p><h4>1. Veritabanı Yapısı</h4><p>Öncelikle, <strong>outbox</strong> tablosu veritabanında şöyle görünür:</p><pre>CREATE TABLE outbox (<br>    id BIGINT AUTO_INCREMENT PRIMARY KEY,<br>    aggregate_id BIGINT NOT NULL,<br>    message_type VARCHAR(255) NOT NULL,<br>    payload TEXT NOT NULL,<br>    status VARCHAR(50) DEFAULT &#39;PENDING&#39;,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);</pre><ul><li><strong>aggregate_id</strong>: Mesajın ilişkili olduğu ana iş öğesi (örneğin, sipariş ID’si).</li><li><strong>message_type</strong>: Mesaj türü (örneğin, OrderCreated).</li><li><strong>payload</strong>: Mesajın içeriği, genellikle JSON formatında.</li><li><strong>status</strong>: Mesajın durumu (başlangıçta PENDING, daha sonra SENT veya FAILED olabilir).</li><li><strong>created_at</strong>: Mesajın oluşturulma zamanı.</li><li><strong>updated_at</strong>: Mesajın güncellenme zamanı.</li></ul><h4>2. Spring Boot Yapısı</h4><p>a. Maven Bağımlılıkları</p><p>pom.xml dosyanıza gerekli bağımlılıkları ekleyin:</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Spring Boot Starter Web --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- Spring Boot Starter Data JPA (Hibernate) --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- H2 Database (veya gerçek bir veritabanı kullanabilirsiniz) --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>        &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>        &lt;scope&gt;runtime&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- Spring Boot Starter AMQP (RabbitMQ için) --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- Jackson (JSON işleme için) --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>        &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- Spring Boot Starter Test --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>b. JPA Entity: Outbox Mesaj Tablosu</p><p>OutboxMessage JPA entity&#39;si, mesajların outbox tablosuna kaydedilmesini sağlar:</p><pre>import javax.persistence.*;<br>import java.time.LocalDateTime;<br>@Entity<br>public class OutboxMessage {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    @Column(nullable = false)<br>    private Long aggregateId;<br>    @Column(nullable = false)<br>    private String messageType;<br>    @Column(nullable = false, columnDefinition = &quot;TEXT&quot;)<br>    private String payload;<br>    @Column(nullable = false)<br>    private String status = &quot;PENDING&quot;;  // &#39;PENDING&#39;, &#39;SENT&#39;, &#39;FAILED&#39;<br>    @Column(nullable = false)<br>    private LocalDateTime createdAt = LocalDateTime.now();<br>    @Column(nullable = false)<br>    private LocalDateTime updatedAt = LocalDateTime.now();<br>    // Getters and setters...<br>}</pre><p>c. JPA Repository: Outbox Mesajları Repository</p><p>Mesajları almak ve güncellemek için bir repository sınıfı oluşturuyoruz:</p><pre>import org.springframework.data.jpa.repository.JpaRepository;<br>public interface OutboxMessageRepository extends JpaRepository&lt;OutboxMessage, Long&gt; {<br>    // PENDING durumundaki mesajları alalım<br>    List&lt;OutboxMessage&gt; findByStatus(String status);<br>}</pre><p>d. Mesaj Gönderme Servisi</p><p>Mesajları outbox tablosuna kaydederken aynı zamanda mesajları dışa gönderen servis:</p><pre>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public class OutboxService {<br><br>    @Autowired<br>    private OutboxMessageRepository outboxMessageRepository;<br><br>    @Autowired<br>    private RabbitTemplate rabbitTemplate;<br><br>    private static final String QUEUE_NAME = &quot;order-events&quot;;<br><br>    // Mesajları veritabanına kaydeder<br>    public void saveMessage(Long aggregateId, String messageType, String payload) {<br>        OutboxMessage message = new OutboxMessage();<br>        message.setAggregateId(aggregateId);<br>        message.setMessageType(messageType);<br>        message.setPayload(payload);<br>        outboxMessageRepository.save(message);<br>    }<br><br>    // Outbox&#39;tan mesajları alıp, kuyruğa gönderir<br>    public void processPendingMessages() {<br>        List&lt;OutboxMessage&gt; pendingMessages = outboxMessageRepository.findByStatus(&quot;PENDING&quot;);<br>        <br>        for (OutboxMessage message : pendingMessages) {<br>            try {<br>                // RabbitMQ kuyruğuna gönderiyoruz<br>                rabbitTemplate.convertAndSend(QUEUE_NAME, message.getPayload());<br><br>                // Mesajı &#39;SENT&#39; olarak güncelliyoruz<br>                message.setStatus(&quot;SENT&quot;);<br>                outboxMessageRepository.save(message);<br>            } catch (Exception e) {<br>                // Mesaj gönderme başarısız olursa &#39;FAILED&#39; olarak işaretliyoruz<br>                message.setStatus(&quot;FAILED&quot;);<br>                outboxMessageRepository.save(message);<br>            }<br>        }<br>    }<br>}</pre><p>e. Mesaj Gönderme ve İşlem Servisi</p><p>Bir sipariş oluşturma ve outbox’a mesaj ekleme işlemi:</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class OrderService {<br><br>    @Autowired<br>    private OutboxService outboxService;<br><br>    public void createOrder(Long orderId, String orderDetails) {<br>        // Siparişi veritabanına kaydeder (bu örnekte basitçe simüle ettik)<br>        <br>        // Sipariş oluşturulduğunda, outbox tablosuna bir mesaj ekleyelim<br>        String payload = &quot;{ \&quot;orderId\&quot;: &quot; + orderId + &quot;, \&quot;orderDetails\&quot;: \&quot;&quot; + orderDetails + &quot;\&quot; }&quot;;<br>        outboxService.saveMessage(orderId, &quot;OrderCreated&quot;, payload);<br>    }<br>}</pre><p>f. Uygulama Başlatma ve Scheduled Task</p><p>Mesajların dışa gönderilmesini otomatik hale getirebilmek için bir <strong>scheduled task</strong>:</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Component;<br>@Component<br>public class MessageProcessor {<br>    @Autowired<br>    private OutboxService outboxService;<br>    // Her 10 saniyede bir Outbox&#39;taki mesajları kontrol et ve gönder<br>    @Scheduled(fixedRate = 10000)<br>    public void processMessages() {<br>        outboxService.processPendingMessages();<br>    }<br>}</pre><p>g. Konfigürasyon</p><p>RabbitMQ için basit bir Spring Boot konfigürasyonu:</p><pre>import org.springframework.amqp.rabbit.annotation.EnableRabbit;<br>import org.springframework.context.annotation.Configuration;<br>@Configuration<br>@EnableRabbit<br>public class RabbitConfig {<br>    // RabbitMQ konfigürasyon ayarları buraya eklenebilir. Nasıl yogurt yemek istiyorsan.<br>}</pre><h3>Retry Mekanizması Tasarımı</h3><p>Bir retry mekanizması tasarlandığında, mesajların <strong>tekrar gönderim</strong> işlemleri güvenli ve verimli bir şekilde yapılmalıdır. Aşağıda, retry mekanizmasının nasıl tasarlanabileceğine dair bir açıklama ve Java kodu örneği sunulmuştur.</p><h3>Retry Mekanizmasının Temel Prensipleri</h3><ol><li><strong>Max Retry Sayısı</strong>:</li></ol><ul><li>Bir mesajın yeniden gönderilme sayısını sınırlamak gerekir. Aksi takdirde, sonsuz döngüler oluşabilir. Genellikle, bir mesajın yeniden gönderilme sayısı belirli bir sınırla (maxRetries) sınırlanır.</li></ul><ol><li><strong>Backoff Stratejisi (Geriye Dönüş)</strong>:</li></ol><ul><li>Her yeniden denemede, önceki başarısız denemelere bağlı olarak bekleme süresi arttırılabilir. Bu, mesajların sürekli olarak denendiği ama çok fazla kaynak tüketmediği anlamına gelir. <strong>Exponential Backoff</strong> (Üssel Geriye Dönüş) yaygın bir yöntemdir, burada her başarısız denemeden sonra bekleme süresi çifte artar.</li></ul><ol><li><strong>Durum Güncelleme</strong>:</li></ol><ul><li>Her yeniden denemede, mesajın durumunun güncellenmesi gerekir. Eğer maksimum yeniden deneme sayısına ulaşıldıysa, mesajın durumu FAILED olarak işaretlenebilir. Bunun dışında, her başarılı denemede durum SENT olarak değiştirilir.</li></ul><ol><li><strong>Loglama ve İzleme</strong>:</li></ol><ul><li>Retry işlemlerinde hata oluştuğunda, hata mesajlarının loglanması ve izlenmesi önemlidir. Bu sayede hangi mesajların neden başarısız olduğu daha kolay analiz edilebilir.</li></ul><ol><li><strong>Yedekleme ve Olay Yönetimi</strong>:</li></ol><ul><li>Eğer retry işlemleri sürekli başarısız oluyorsa, bu mesajları başka bir kuyruğa yönlendirebilir (örneğin, bir “dead-letter” kuyruğu), böylece sorunlu mesajlar daha ileri bir işlem için gözden geçirilebilir.</li></ul><h3>Java ile Retry Mekanizması</h3><p>Şimdi, retry mekanizmasını uygulamak için <strong>Spring Boot</strong> ve <strong>RabbitMQ</strong> kullandığımız örneği genişleterek retry mekanizmasını ekleyelim.</p><h4>1. OutboxService Güncellemesi</h4><p>Mesaj gönderme işlemi sırasında retry mekanizması ekleyeceğiz. Ayrıca her yeniden denemede, belirli bir bekleme süresi (backoff) ekleyeceğiz.</p><pre>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br>import java.util.List;<br>import java.util.concurrent.TimeUnit;<br><br>@Service<br>public class OutboxService {<br>    @Autowired<br>    private OutboxMessageRepository outboxMessageRepository;<br>    @Autowired<br>    private RabbitTemplate rabbitTemplate;<br>    private static final String QUEUE_NAME = &quot;order-events&quot;;<br>    private static final int MAX_RETRIES = 3; // Maksimum yeniden deneme sayısı<br>    private static final int INITIAL_BACKOFF = 1000; // Başlangıç bekleme süresi (ms)<br>    private static final int BACKOFF_MULTIPLIER = 2; // Üssel artış<br>    // Mesajları veritabanına kaydeder<br>    public void saveMessage(Long aggregateId, String messageType, String payload) {<br>        OutboxMessage message = new OutboxMessage();<br>        message.setAggregateId(aggregateId);<br>        message.setMessageType(messageType);<br>        message.setPayload(payload);<br>        outboxMessageRepository.save(message);<br>    }<br>    // Outbox&#39;tan mesajları alıp, kuyruğa gönderir<br>    public void processPendingMessages() {<br>        List&lt;OutboxMessage&gt; pendingMessages = outboxMessageRepository.findByStatus(&quot;PENDING&quot;);<br>        <br>        for (OutboxMessage message : pendingMessages) {<br>            boolean sent = false;<br>            int retryCount = 0;<br>            while (!sent &amp;&amp; retryCount &lt;= MAX_RETRIES) {<br>                try {<br>                    // RabbitMQ kuyruğuna gönderiyoruz<br>                    rabbitTemplate.convertAndSend(QUEUE_NAME, message.getPayload());<br>                    // Mesaj başarıyla gönderildi, durumunu güncelle<br>                    message.setStatus(&quot;SENT&quot;);<br>                    outboxMessageRepository.save(message);<br>                    sent = true;<br>                } catch (Exception e) {<br>                    // Hata oluştu, retry yapıyoruz<br>                    retryCount++;<br>                    if (retryCount &gt; MAX_RETRIES) {<br>                        // Maksimum deneme sayısına ulaşıldıysa, durumu FAILED olarak güncelle<br>                        message.setStatus(&quot;FAILED&quot;);<br>                        outboxMessageRepository.save(message);<br>                    } else {<br>                        // Bekleme süresi arttırarak yeniden deniyoruz<br>                        long backoffTime = INITIAL_BACKOFF * (long) Math.pow(BACKOFF_MULTIPLIER, retryCount);<br>                        try {<br>                            TimeUnit.MILLISECONDS.sleep(backoffTime);<br>                        } catch (InterruptedException interruptedException) {<br>                            Thread.currentThread().interrupt();<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Açıklamalar:</h3><ul><li><strong>MAX_RETRIES</strong>: Maksimum yeniden deneme sayısını belirler. Bir mesaj, bu sayıya kadar yeniden denenebilir. Bu sayı aşılırsa, mesaj FAILED olarak işaretlenir.</li><li><strong>INITIAL_BACKOFF</strong>: İlk başarısız denemeden sonra bekleme süresi. Başlangıçta bu değeri milisaniye cinsinden belirleriz.</li><li><strong>BACKOFF_MULTIPLIER</strong>: Üssel artış katsayısı. Her başarısız denemede bekleme süresi bu kat sayısı ile arttırılır.</li><li><strong>TimeUnit.MILLISECONDS.sleep(backoffTime)</strong>: Her başarısız denemeden sonra belirli bir süre bekleriz. Bu süre üssel bir şekilde artar.</li><li><strong>Exception Handling</strong>: Mesaj iletimi sırasında bir hata meydana gelirse, retry yapılır. Eğer belirlenen maksimum sayıda deneme yapılmışsa, mesajın durumu FAILED olarak değiştirilir.</li></ul><h3>2. Scheduled Task Güncellemesi</h3><p>Mesajların dışa iletilmesini düzenli aralıklarla yapan Scheduled task&#39;ı, retry mekanizması eklenmiş versiyonla aynı şekilde çalışacak. Yalnızca önceki işlevde retry işlemi eklendi.</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class MessageProcessor {<br>    @Autowired<br>    private OutboxService outboxService;<br>    // Her 10 saniyede bir Outbox&#39;taki mesajları kontrol et ve gönder<br>    @Scheduled(fixedRate = 10000)<br>    public void processMessages() {<br>        outboxService.processPendingMessages();<br>    }<br>}</pre><h3>3. RabbitMQ Konfigürasyonu</h3><p>RabbitMQ’da retry ile ilgili ek bir yapılandırma gerekmez, ancak retry yapılmadığı durumlarda <strong>dead-letter queue (DLQ)</strong> kullanmak faydalı olabilir. Yani, retry işlemi belirli bir sınırda başarısız olursa, mesajlar başka bir kuyruğa (dead-letter queue) yönlendirilip daha sonra manuel veya otomatik olarak işlenebilir.</p><p>Örnek olarak, application.yml dosyasına <strong>DLQ</strong> konfigürasyonu ekleyebilirsiniz:</p><pre>spring:<br>  rabbitmq:<br>    listener:<br>      simple:<br>        retry:<br>          enabled: true<br>          max-attempts: 3<br>          initial-interval: 1000ms<br>          multiplier: 2.0<br>          max-interval: 10000ms</pre><h3>4. Dead-letter Queue (Opsiyonel)</h3><p>Dead-letter queue, başarısız mesajları takip etmek ve manuel müdahale etmek için iyi bir yöntemdir. Eğer retry işlemi başarısız olursa, mesajları başka bir kuyrukta depolayabilirsiniz.</p><pre>@Bean<br>public Queue deadLetterQueue() {<br>    return QueueBuilder.durable(&quot;deadLetterQueue&quot;).build();<br>}<br><br>@Bean<br>public DirectExchange deadLetterExchange() {<br>    return new DirectExchange(&quot;deadLetterExchange&quot;);<br>}<br>@Bean<br>public Binding bindingDeadLetterQueue() {<br>    return BindingBuilder.bind(deadLetterQueue())<br>            .to(deadLetterExchange())<br>            .with(&quot;deadLetterRoutingKey&quot;);<br>}</pre><h3>5. Loglama ve İzleme</h3><p>Her başarısız denemede ve başarılı mesaj gönderiminde <strong>loglama</strong> yapmak, retry işlemlerinin izlenmesi açısından önemlidir.</p><pre>private static final Logger logger = LoggerFactory.getLogger(OutboxService.class);<br>// Hata olduğunda<br>logger.error(&quot;Message sending failed. Retrying... attempt {}/{}&quot;, retryCount, MAX_RETRIES);<br>// Başarıyla gönderildiğinde<br>logger.info(&quot;Message successfully sent to the queue: {}&quot;, message.getId());</pre><h3>Sonuç</h3><p>Bu örnekte <strong>Transactional Outbox</strong> desenini Java Spring Boot ile başarılı bir şekilde uyguladık. Mikroservislerin arasında güvenli ve tutarlı bir mesaj iletimi sağladık. <strong>Veritabanı ve mesajlaşma sistemleri</strong> arasındaki tutarsızlıkları önlemek için mesajlar <strong>outbox</strong> tablosunda saklanırken, arka planda çalışan bir işlem bunları dışa gönderdi.</p><p>Uygulama şu şekilde çalışır:</p><ul><li>Bir sipariş oluşturulduğunda, OrderService outbox tablosuna bir mesaj ekler.</li><li>MessageProcessor sınıfı, her 10 saniyede bir bu mesajları kontrol eder ve RabbitMQ kuyruğuna gönderir.</li><li>Eğer mesaj başarılı bir şekilde gönderildiyse, durumu SENT olarak güncellenir, aksi halde FAILED olarak işaretlenir.</li><li><strong>Retry Mekanizması</strong>: Mesaj kuyruğuna iletimi başarısız olan mesajlar, belirli bir süre bekledikten sonra yeniden denenir. Başarısız denemeler bir sınır koyularak durdurulur ve mesaj FAILED olarak işaretlenir.</li><li><strong>Backoff Stratejisi</strong>: Her başarısız denemeden sonra bekleme süresi arttırılır (exponential backoff).</li><li><strong>Loglama ve İzleme</strong>: Hataların izlenebilirliği sağlanır ve gerektiğinde mesajlar dead-letter queue&#39;ya yönlendirilir.</li></ul><p>Bu yaklaşım, mesajların kaybolmamasını ve sistemin tutarlı bir şekilde çalışmasını sağlar.</p><p><strong>&quot;Microservices Patterns: With examples in Java” by Chris Richardson</strong>:</p><ul><li>Kitap, mikroservisler için yaygın desenleri ele alır ve <strong>Transactional Outbox</strong> desenini detaylı bir şekilde açıklar. Ayrıca, desenin nasıl uygulanacağına dair örnekler ve Java kodları sunar. Ek olarak bu konu özelinde 98. sayfaya bakmak yeterldir.</li><li><a href="https://www.amazon.com/Microservices-Patterns-examples-Chris-Richardson/dp/1617294543">Link: Microservices Patterns on Amazon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=148aa1063958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Parallelism ve Concurrency: Warhammer Dünyasında Bir Görev!]]></title>
            <link>https://cedellalahmet.medium.com/java-parallelism-ve-concurrency-warhammer-d%C3%BCnyas%C4%B1nda-bir-g%C3%B6rev-900008a60593?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/900008a60593</guid>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 14:23:19 GMT</pubDate>
            <atom:updated>2024-12-29T15:27:45.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yFwpWZ40QOQZuCm7yyaOg.jpeg" /></figure><p><em>Düşün bir an, bir İmparatorluk savaşında yüzlerce askerin aynı anda savaşmak için hareket ettiğini… Fakat her birinin farklı bir hedefi, amacı ve etkileşimleri var. Bu durum, yazılım mühendisliğinde karşılaştığımız “paralel işlem” ve “eşzamanlılık” kavramlarına benzer. Ama dikkat et: Her askerin doğru zamanda doğru şekilde hareket etmesi gerekiyor. Yoksa sistem çökebilir, ya da daha kötü… Chaos dünyasının karanlık güçleri devreye girer!</em></p><h3>Paralelizm ve Eşzamanlılık: İki Yüce Güç</h3><p>İlk önce <strong>paralelizm</strong> ve <strong>eşzamanlılık</strong> arasındaki farkı netleştirerek başlamak önemli. Bu terimler genellikle birbirinin yerine kullanılsa da aslında farklı anlamlara gelirler.</p><h3>Paralelizm (Parallelism)</h3><p><strong>Paralelizm</strong>, birden fazla işlemci veya çekirdeği kullanarak birden fazla işlemin aynı anda çalışmasını sağlar. Bu, <strong>gerçekten aynı anda çalışan</strong> kod parçalarının olduğu bir durumdur. Yani, her işlem kendi bağımsız yolunda ilerler.</p><p>Warhammer’daki bir savaşta, her bir askerin kendi görevini yerine getirdiğini düşün. Bir grup okçunun düşmanı vurduğu, bir grup kalkanlı askerinin ise savunma yaptığı anı hayal et. Aynı anda farklı işler yapılıyor, ve hepsi kendi yolunda paralel bir şekilde ilerliyor. Bu, paralel programlamanın özü.</p><p><strong>Java’daki paralel işlem örneği</strong>:</p><pre>import java.util.stream.IntStream;<br>public class ParallelExample {<br> public static void main(String[] args) {<br> // Paralel işlemle 1&#39;den 100&#39;e kadar olan sayıları topla<br> int sum = IntStream.range(1, 101)<br> .parallel() // Paralel işleme başla<br> .sum();<br> System.out.println(“Sum is: “ + sum);<br> }<br>}</pre><p>Burada parallel() metodu, işlemin paralel olarak yapılmasını sağlıyor. Birden fazla çekirdek kullanarak bu hesaplama daha hızlı yapılır. Tıpkı Warhammer’da paralel görevler yapan askerlere benzer şekilde!</p><h3>Eşzamanlılık (Concurrency)</h3><p><strong>Eşzamanlılık</strong>, aynı anda birden fazla görev üzerinde çalışmanın <strong>mantıksal</strong> yönetimidir. Her ne kadar görevler zaman dilimleri içinde paylaşılsa da, genellikle hepsi bir işlemci çekirdeğinde sırasıyla gerçekleştirilir. Eşzamanlılık, <strong>aynı anda</strong> birden fazla görevi koordine etmeyi amaçlar, ancak bu görevler <strong>gerçekten aynı anda çalışmaz</strong>.</p><p>Bir örnekle açıklayalım: Warhammer evreninde bir komutanın tüm birlikleri koordine etmesi gibi. Aynı anda çok sayıda birliğe emir veriyor olabilir, ancak her birlik için sırayla düşünmek, komutanın zaman dilimlerini paylaşması gerekecektir. Bu da eşzamanlılıkla yapılan bir yönetim şeklidir.</p><p>Java’da eşzamanlılık örneği:</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>public class ConcurrencyExample {<br> public static void main(String[] args) {<br> ExecutorService executor = Executors.newFixedThreadPool(3); // 3 thread&#39;lik bir havuz<br> executor.submit(() -&gt; System.out.println(“Görev 1 çalışıyor”));<br> executor.submit(() -&gt; System.out.println(“Görev 2 çalışıyor”));<br> executor.submit(() -&gt; System.out.println(“Görev 3 çalışıyor”));<br> executor.shutdown();<br> }<br>}</pre><p>Burada <strong>ExecutorService</strong> kullanılarak görevler bir iş havuzuna atanır. Her bir görev sırasıyla çalıştırılır, ancak aynı anda çalışıyor gibi görünür.</p><h3>Zorluklar ve Gerçek Hayat Senaryoları</h3><p>Warhammer evreninden bir örnekle bu konuyu daha derinlemesine inceleyelim. Bir Warhammer komutanının görevini en iyi şekilde yerine getirmesi için, her askerin doğru zamanda doğru şeyleri yapması gerekir. Ama pratikte, bazı sorunlar çıkar.</p><h3>1. Veri Yarışı (Race Conditions):</h3><p>Bir askerin, aynı anda düşmana karşı aynı hedefi vurmak istemesi gibi bir durumu düşün. Birinin oku diğerinden önce fırlatılmalı. Eğer her ikisi de aynı anda hareket ederse, her şey karışır.</p><p>Java’da veri yarışı şöyle çözülür:</p><pre>class Soldier {<br>private int health;<br>public synchronized void attack() {<br> health -= 10; // Sadece bir thread aynı anda bu methodu çalıştırabilir.<br> }<br>}</pre><p>Burada synchronized anahtar kelimesi, sadece bir iş parçacığının aynı anda attack() metodunu çalıştırabilmesini sağlar. Aksi halde, çakışmalar meydana gelir.</p><h3>2. Ölü Kilitlenmeler (Deadlocks):</h3><p>Warhammer’daki bir senaryo düşün: Bir grup askerin birbirine kilitlenmesi ve hareket edememesi. Kod tarafında, iki ya da daha fazla iş parçacığının birbirinden kaynak bekleyerek sonsuza kadar beklemesi bir <strong>deadlock</strong> durumudur.</p><pre>class Army {<br> private final Object lock1 = new Object();<br> private final Object lock2 = new Object();<br>public void attack() {<br> synchronized (lock1) {<br> synchronized (lock2) {<br> // Kod kilitlenebilir<br> }<br> }<br> }<br>}</pre><p>Bu durumda, lock1 ve lock2 kilitleri birbirini bekler ve bu da kodun çalışmaması ile sonuçlanır. Bu tür problemleri önlemek için dikkatli bir kaynak yönetimi gereklidir.</p><h3>Warhammer’dan İlginç Bir Durum: Eşzamanlılık ile Paralelizm Birleşiyor!</h3><p>Şimdi hayal et: Warhammer’daki iki ordu karşı karşıya geliyor. Bir taraf paralel savaşçıları yönetiyor (her biri aynı anda farklı görevleri yapıyor), diğer taraf ise eşzamanlı yönetimle tüm birliği koordine ediyor. Amaçları aynı, ama birbirleriyle nasıl etkileşime gireceklerini çok iyi düşünmeleri gerekiyor.</p><p>Java’da, paralel ve eşzamanlı işlemleri birleştirmek oldukça yaygındır. <strong>CompletableFuture</strong> gibi yapılar, her iki dünyayı birleştirmenizi sağlar:</p><pre>import java.util.concurrent.CompletableFuture;<br>public class CombinedExample {<br> public static void main(String[] args) {<br> CompletableFuture&lt;Void&gt; future1 = CompletableFuture.runAsync(() -&gt; System.out.println(&quot;Paralel Görev 1&quot;));<br> CompletableFuture&lt;Void&gt; future2 = CompletableFuture.runAsync(() -&gt; System.out.println(&quot;Paralel Görev 2&quot;));<br>// Eşzamanlı olarak iki görevi bekle<br> CompletableFuture&lt;Void&gt; combinedFuture = CompletableFuture.allOf(future1, future2);<br> combinedFuture.join(); // Her iki görev bitene kadar bekle<br> System.out.println(“Her iki görev de tamamlandı!”);<br> }<br>}</pre><p>Burada, iki görev paralel çalışırken, tamamlanmalarını eşzamanlı olarak bekliyoruz. Bu, hem paralel işlemi hem de eşzamanlı yönetimi aynı anda kullanmamızı sağlıyor.</p><h3>Sonuç: Kaos’tan Düzen Doğar!</h3><p>Tıpkı Warhammer’daki gibi, yazılım mühendisliğinde de paralelizm ve eşzamanlılık bir denge meselesidir. İyi yönetilmediklerinde işler çığırından çıkabilir; fakat doğru stratejiyle hem verimli hem de güvenli bir şekilde çalışabiliriz. Tıpkı bir komutanın savaş meydanındaki mükemmel koordinasyonu gibi, doğru paralel ve eşzamanlı yöntemlerle sistemlerimizi verimli hale getirebiliriz.</p><p>Unutma: Kaos, kötü planlamanın ve yönetimin sonucudur. Dikkatli bir şekilde planlama ve doğru araçları kullanmak her zaman zaferi getirir.</p><p><strong>synchronized</strong> anahtar kelimesini derinlemesine inceleyerek bu konuyu biraz daha açabiliriz. Java&#39;daki eşzamanlılık ve paralelizm bağlamında synchronized çok önemli bir rol oynar, çünkü bu anahtar kelime, bir iş parçacığının belirli bir kod bloğunu aynı anda yalnızca bir iş parçacığının çalıştırabilmesini sağlar. Bu, <strong>yarış durumu (race condition)</strong> gibi istenmeyen senaryoları engellemeye yardımcı olur.</p><h3>Synchronized: Savaş Alanında Güvenli Bir Alan Oluşturmak</h3><p>Java’da çoklu iş parçacığı çalıştırırken, birden fazla iş parçacığı aynı veriye erişmeye çalıştığında veri tutarsızlıkları (race condition) meydana gelebilir. Bu durumu engellemek için <strong>synchronized</strong> anahtar kelimesi kullanılır. Tıpkı Warhammer’daki bir komutanın farklı birimleri birbirinden izole edip her birine belirli bir görev vermesi gibi, synchronized da aynı anda yalnızca bir iş parçacığının belirli bir kod bloğunu çalıştırmasını sağlar.</p><h3>Synchronized Anahtar Kelimesinin Çalışma Prensibi</h3><p>Synchronized anahtar kelimesi, bir iş parçacığının erişmekte olduğu bir kaynağın diğer iş parçacıkları tarafından erişilememesini sağlar. Bu, özellikle <strong>paylaşılan kaynaklara</strong> erişim sırasında, işlemlerin sırayla yapılmasını garantiler.</p><h3>Metodun Synchronized Olması</h3><p>Bir metodun synchronized olarak tanımlanması, o metodun <strong>tek bir iş parçacığı tarafından aynı anda çalıştırılabilmesini</strong> sağlar. Diğer iş parçacıkları bu metodu çalıştırmak isterse, önce bu iş parçacığının bitmesini beklemek zorundadırlar.</p><p>Daha önceki örnek üzerinden bakarsak:</p><pre>class Soldier {<br> private int health;<br>public synchronized void attack() {<br> // Bu metod sadece bir iş parçacığı tarafından aynı anda çalıştırılabilir<br> health -= 10;<br> System.out.println(“Health: “ + health);<br> }<br>}</pre><p>Burada attack() metodunu <strong>synchronized</strong> olarak işaretledik. Bu, sadece bir iş parçacığının attack() metodunu çalıştırmasına izin verir. Eğer başka bir iş parçacığı aynı anda bu metodu çağırmaya çalışırsa, o iş parçacığı bekleyecek ve attack() metodu tamamlandıktan sonra çalışmaya başlayacaktır.</p><p><strong>Savaş Alanında Örnek</strong>: Diyelim ki, Warhammer’daki bir okçu, bir düşmanı vuruyor ve okunu bir hedefe doğru fırlatıyor. Eğer aynı anda başka bir okçu da aynı hedefi vurmak istiyorsa, birinin okunun daha önce gitmesi gerekir. Buradaki “synchronized” işlevi, okçulardan sadece birinin aynı anda ok fırlatabilmesini sağlamaktadır.</p><h3>Synchronized ve Nesne Seviyesi Kilitleme</h3><p>Bir metodun synchronized olmasının yanı sıra, aynı zamanda <strong>nesne seviyesinde</strong> de kilitleme yapılır. Bu, bir nesneye ait bir metodun <strong>tek bir iş parçacığı tarafından</strong> çalıştırılmasını sağlar. Yani, başka bir iş parçacığı aynı nesne üzerinde başka bir synchronized metodu çalıştırmak isterse, önce bu işlemi beklemek zorunda kalır.</p><p>Örnek:</p><pre>class Soldier {<br> private int health;<br>public synchronized void attack() {<br> health -= 10;<br> }<br>public synchronized void heal() {<br> health += 5;<br> }<br>}</pre><p>Bu durumda, bir iş parçacığı attack() metodunu çalıştırırken, başka bir iş parçacığı heal() metodunu çalıştırmak isterse, beklemek zorunda kalacaktır. Çünkü her iki metod da aynı nesne üzerinde işlem yapmaktadır ve yalnızca bir iş parçacığının her iki metodu da aynı anda çalıştırmasına izin verilir.</p><h3>Synchronized ve Class Seviyesi Kilitleme</h3><p>Eğer statik bir metodun <strong>synchronized</strong> olmasını sağlarsak, o metodun <strong>tüm sınıf için bir iş parçacığı tarafından</strong> çalıştırılmasına izin veririz. Bu durumda, sınıf seviyesinde bir kilit (lock) uygulanır.</p><pre>class Army {<br> private static int armyCount;<br>public synchronized static void incrementArmyCount() {<br> armyCount++;<br> }<br>}</pre><p>Bu durumda, sınıfın herhangi bir iş parçacığı incrementArmyCount() metodunu çağırırsa, diğer iş parçacıkları bu metodu çalıştırana kadar beklemek zorunda kalır. Çünkü bu metod statiktir ve tüm sınıfı etkilemektedir.</p><p><strong>Warhammer’dan bir örnek</strong>: Farz edelim ki bir Ork komutanı, savaşta kazandığı her zaferi kaydediyor. Her zafer kazandığında, <strong>ork ordusunun zafer sayısını</strong> artırmak için incrementArmyCount() metodu çağrılıyor. Eğer çok sayıda Ork komutanı bu metodu aynı anda çalıştırmaya çalışıyorsa, yalnızca bir komutan bu işlemi gerçekleştirebilir.</p><h3>Synchronized ile Yarış Durumlarını Önlemek</h3><h3>Yarış Durumu (Race Condition)</h3><p>Yarış durumu, birden fazla iş parçacığının aynı anda aynı kaynağa erişmeye çalıştığında ortaya çıkar. Bu durumda, her iş parçacığı kendine ait veriyi değiştirmeye çalışır ve sonuçta veri tutarsızlığı meydana gelir.</p><p>Örneğin:</p><pre>class Soldier {<br>    private int health = 100;<br>public void attack() {<br>        health -= 10; // Yarış durumu: Aynı anda birden fazla thread bu satırı çalıştırırsa hata olabilir.<br>    }<br>}</pre><p>Eğer bu kod çoklu iş parçacığıyla çalıştırılırsa, aynı anda birden fazla iş parçacığı health değişkenini değiştirmeye çalışabilir. Bu durumda, bir iş parçacığı sağlığı azaltırken diğer bir iş parçacığı aynı değeri okur ve değiştirebilir, bu da hatalı sonuçlara yol açar. Bu gibi durumları engellemek için synchronized anahtar kelimesini kullanarak işlemlerin sırasıyla yapılmasını sağlarız.</p><pre>class Soldier {<br>    private int health = 100;<br>public synchronized void attack() {<br>        health -= 10; // Sadece bir thread bu işlemi gerçekleştirebilir.<br>    }<br>}</pre><p>Bu şekilde, her seferinde yalnızca bir iş parçacığı attack() metodunu çalıştırabilir ve veri tutarlılığı korunur.</p><h3>Synchronized ile Deadlock (Ölü Kilitlenme) Durumları</h3><p><strong>Deadlock</strong> (ölü kilitlenme), bir iş parçacığının diğer bir iş parçacığının kaynaklarını beklerken, ikinci iş parçacığının da ilk iş parçacığının kaynaklarını beklemesi durumudur. Bu, her iki iş parçacığının da birbirini bekleyerek sonsuza kadar kilitlenmesine yol açar.</p><p>Bir deadlock senaryosu şöyle olabilir.</p><pre>class Army {<br>    private final Object lock1 = new Object();<br>    private final Object lock2 = new Object();<br>public void attack() {<br>        synchronized (lock1) {<br>            synchronized (lock2) {<br>                // İşlem yapılacak<br>            }<br>        }<br>    }<br>    public void defend() {<br>        synchronized (lock2) {<br>            synchronized (lock1) {<br>                // İşlem yapılacak<br>            }<br>        }<br>    }<br>}</pre><p>Burada, attack() metodu önce lock1&#39;i, sonra lock2&#39;yi kilitliyor. Diğer taraftan, defend() metodu önce lock2&#39;yi, sonra lock1&#39;i kilitliyor. Eğer bir iş parçacığı attack() metodunu çalıştırıyorsa ve diğer iş parçacığı defend() metodunu çalıştırıyorsa, her iki iş parçacığı da birbirini bekleyecek ve hiçbiri işlem tamamlanamayacaktır. Bu durum bir deadlock durumudur.</p><p>Deadlock’u önlemek için dikkatli bir şekilde kilitleri yönetmek ve sıralamak gerekir.</p><h3>Sonuç: Güvenli ve Etkili Yönetim</h3><p>Synchronized anahtar kelimesi, çoklu iş parçacığıyla çalışırken <strong>paylaşılan kaynakların güvenli bir şekilde yönetilmesi</strong> için kritik bir araçtır. Warhammer’daki komutanın, her bir birliğin doğru zamanda doğru yerde olmasını sağlaması gibi, yazılımda da synchronized sayesinde iş parçacıkları arasındaki etkileşim düzenlenebilir. Ancak, dikkatli bir şekilde yönetilmezse, <strong>yarış durumu</strong>, <strong>deadlock</strong> gibi karmaşık sorunlar ortaya çıkabilir. Bu nedenle, paralel ve eşzamanlı programlama yaparken dikkatli olmak, sistemin verimli ve güvenli çalışmasını sağlar.</p><h3>Kaynaklar</h3><ol><li><strong>Java Concurrency in Practice — Brian Goetz</strong></li></ol><ul><li>Bu yazının çıkmasına vesile olan kitaptır. Okuma sırasında edindiğim notları kendi yorumum ile sunulmasını iceriyor.</li><li>Bu kitap, Java’daki eşzamanlılık ve paralel programlama konularında çok kapsamlı bir kaynaktır. synchronized anahtar kelimesinin nasıl çalıştığı ve çoklu iş parçacığı programlaması ile ilgili derinlemesine bilgi sağlar. Java&#39;nın eşzamanlılık mekanizmalarına dair pek çok örnek ve açıklama sunmaktadır.</li><li><a href="https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601">Java Concurrency in Practice (Amazon)</a></li></ul><ol><li><strong>The Java™ Tutorials — Concurrency</strong></li></ol><ul><li>Oracle’ın resmi Java dökümantasyonu, eşzamanlılık hakkında temel kavramları, synchronized anahtar kelimesinin kullanımını ve daha karmaşık iş parçacığı yönetimi konularını ele alır. Oracle&#39;ın bu kaynağı, çok sayıda örnekle açıklamalar yapar.</li><li><a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/">Oracle Java Concurrency Tutorial</a></li></ul><ol><li><strong>Effective Java — Joshua Bloch</strong></li></ol><ul><li>Joshua Bloch’un <em>Effective Java</em> kitabı, Java’da yazılım mühendisliğine dair en iyi uygulamaları içeren çok sayıda bölüm sunar. Bu kitapta, çoklu iş parçacığı ile ilgili çeşitli konular ve eşzamanlılık problemlerinin çözümü ele alınmıştır.</li><li><a href="https://www.amazon.com/Effective-Java-Joshua-Bloch/dp/0134685997">Effective Java (Amazon)</a></li></ul><ol><li><strong>Java: The Complete Reference — Herbert Schildt</strong></li></ol><ul><li>Java’nın temel özelliklerinden ileri düzey konulara kadar her şeyi kapsayan bir başvuru kaynağıdır. synchronized anahtar kelimesinin kullanımı ve çoklu iş parçacığı yönetimi hakkında detaylı açıklamalar içerir.</li><li><a href="https://www.amazon.com/Java-Complete-Reference-11th/dp/1260440230">Java: The Complete Reference (Amazon)</a></li></ul><ol><li><strong>Java Concurrency Utilities (Java API Documentation)</strong></li></ol><ul><li>Java’nın eşzamanlılık API’si, çoklu iş parçacığı uygulamaları geliştirmek için sunulan araçlar hakkında kapsamlı bir dökümantasyon sunar. synchronized dışında, ExecutorService, CountDownLatch, Semaphore ve diğer eşzamanlılık araçları hakkında da bilgi edinmek mümkündür.</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html">Java Concurrency API Documentation</a></li></ul><ol><li><strong>Stack Overflow</strong></li></ol><ul><li>Java’da karşılaşılan eşzamanlılık problemleri hakkında binlerce geliştiricinin soruları ve çözüm önerileri bulunmaktadır. synchronized ve paralel programlama ile ilgili sıkça karşılaşılan hatalar ve çözümleri üzerine geniş bir bilgi birikimi bulabilirsiniz.</li><li><a href="https://stackoverflow.com/">Stack Overflow</a></li></ul><ol><li><strong>JVM Internals: Java Concurrency and Memory Model (YouTube — Oracle)</strong></li></ol><ul><li>Oracle tarafından sunulan bu video serisi, Java’nın eşzamanlılık modelini ve JVM’in çoklu iş parçacığı yönetimini derinlemesine anlamanızı sağlar. Java’nın bellek modeli ve eşzamanlılık yapılarını keşfetmek için harika bir kaynaktır.</li><li><a href="https://www.youtube.com/watch?v=klSzK0P0r9A">JVM Internals: Concurrency and Memory Model</a></li></ul><ol><li><strong>Concurrency in Java — Baeldung</strong></li></ol><ul><li>Baeldung, Java’da eşzamanlılık ve paralel programlama ile ilgili pek çok makale sunar. Burada, synchronized, lock, ExecutorService, ve Java 8 ile gelen paralel akışlar gibi konularda açıklamalar ve örnekler bulabilirsiniz.</li><li>Baeldung — Concurrency in Java</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=900008a60593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NewSQL ile Gerçekten Yeni Neler Var?]]></title>
            <link>https://cedellalahmet.medium.com/newsql-ile-ger%C3%A7ekten-yeni-neler-var-eae5de2cc302?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae5de2cc302</guid>
            <category><![CDATA[newsql]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 21:39:54 GMT</pubDate>
            <atom:updated>2022-04-06T21:43:55.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Aslında bu yazının başlığını b<a href="https://db.cs.cmu.edu/papers/2016/pavlo-newsql-sigmodrec2016.pdf">u linkteki makaleden aldım.</a> Bence bu yazıyı okumadan bu makaleyi okumakta fayda var. Yeni öğrendiğim bir teknolojiyi aktarırken anlatmakta zorlandığım bir çok konuyu daha iyi açıklandığına inanıyorum yinede araştırmalarım sırasında edindiğim bilgileri aktarmaya çalışacağım.</p><p>Çoğu programcı SQL ve ilişkisel veritabanı yönetim sistemlerine veya MySQL , PostgreSQL gibi RDBMS’lere aşinadır. Bu tür mimarilerin temel ilkeleri on yıllardır var. 2000&#39;li yıllardan sonra dağıtılmış, ölçeklenebilir veri ihtiyaçlarını karşılayabilmek için MongoDB veya Cassandra gibi NoSQL çözümleri geldi.</p><p>Ancak, son zamanlarda bu gruba yeni bir çocuk dahil oldu : NewSQL.</p><p><a href="https://en.wikipedia.org/wiki/ACID_(computer_science)">NewSQL, RDBMS’lerin işlemsel ACID</a> (atomiklik, tutarlılık, yalıtım, dayanıklılık) garantilerini ve NoSQL’in yatay ölçeklenebilirliğini birleştirmek isteyen ilişkisel veritabanlarına yönelik yeni bir yaklaşımdır . Her iki dünyanın da en iyisi olan mükemmel bir çözüm gibi geliyor. Peki şimdi ye kadar ortaya çıkmasını geciktiren ne oldu ?</p><p>Veritabanları, 1960&#39;ların ortalarında kodu verilerden ayırma ihtiyacından doğdu. Bu ilk veritabanları çeşitli hususlar göz önünde bulundurularak tasarlanmıştır:</p><ol><li>Veritabanını sorgulayan kullanıcı sayısı sınırlı olmalı.</li><li>Sorgu türleri sınırsızdır — geliştirici istediği herhangi bir sorguyu kullanabilir.</li><li>Donanım oldukça pahalıdır.</li></ol><p>Geliştiricilerin, veritabanına erişimi olan tek kullanıcılar olarak bir terminale etkileşimli sorgular girdiği o günlerde, bu düşünceler alakalı ve değerliydi. <a href="https://db.cs.cmu.edu/papers/2016/pavlo-newsql-sigmodrec2016.pdf">Doğruluk ve tutarlılık, günümüzün performans ve kullanılabilirlik ölçütlerinden ziyade iki önemli ölçüttü. </a>Dikey ölçeklendirme, artan veri gereksinimlerine çözümdü ve veri tabanı geçişi veya kurtarması durumunda taşınacak veri için gereken kesinti süresi katlanılabilirdi.</p><p>Birkaç on yıl sonra, İnternet ve bulut çağındaki veritabanlarından gelen gereksinimler çok daha farklı hale geldi. Veri ölçeği çok büyük ve emtia donanımı 20. yüzyılın maliyetlerine kıyasla çok daha ucuz.</p><p>Veri ölçeği büyüdükçe ve İnternet üzerinden gerçek zamanlı etkileşimler yaygınlaştıkça, veri tabanlarından gelen temel ihtiyaçlar sırasıyla OLAP ve OLTP olmak üzere iki ana kategoriye, Çevrimiçi Analitik İşleme ve Çevrimiçi İşlem İşleme’ye ayrılmaya başladı.</p><p><a href="https://en.wikipedia.org/wiki/Online_analytical_processing">OLAP</a> veritabanları genellikle veri ambarları olarak bilinir. İş zekası operasyonlarında istatistiksel analiz amacıyla tarihsel bir ayak izi depolarlar. OLAP veritabanları bu nedenle toplu işleme için geçici sorgularla salt okunur iş yüklerine odaklanır. Veritabanını sorgulayan kullanıcı sayısı oldukça azdır, genellikle sadece bir şirketin çalışanları geçmiş bilgilere erişebilir.</p><p><a href="https://en.wikipedia.org/wiki/Online_transaction_processing">OLTP</a> veritabanları, gerçek zamanlı kullanıcılar tarafından uygulanan kısa ömürlü ve önceden tanımlanmış sorgularla karakterize edilen, yüksek düzeyde eşzamanlı, işlemsel veri işlemeye karşılık gelir. Normal bir kullanıcının bir e-ticaret web sitesinde yaptığı aramalar ve ürün satın alma işlemleri, işlemsel işlemenin temel örnekleridir. Kullanıcılar, OLAP kullanıcılarına kıyasla daha küçük bir veri alt kümesine erişirken, kullanıcı sayısı oldukça fazladır ve sorgular hem okuma hem de yazma işlemlerini içerebilir. OLTP veritabanlarındaki önemli hususlar bu nedenle yüksek kullanılabilirlik, eşzamanlılık ve performanstır.</p><p>Çoğu web sitesi için, herhangi bir zaman için, veritabanını aynı anda etkin bir şekilde sorgulayan yüzlerce veya binlerce kullanıcı vardır. Bu ölçeği göz önünde bulundurarak, sistemin her dakika kesintiye uğraması daha büyük şirketlere binlerce, <a href="https://www.businessinsider.nl/amazon-prime-day-website-issues-cost-it-millions-in-lost-sales-2018-7/?international=true&amp;r=US">hatta milyonlarca dolara</a> mal olabileceğinden, yüksek düzeyde kullanılabilir olması gerekir .</p><p>Web sitelerinde, kullanıcılar tarafından yapılan sorgular önceden tanımlanmıştır; kullanıcıların istedikleri herhangi bir sorguyu yürütmek için veritabanının terminaline erişimi yoktur. Sorgular uygulama mantığına gömülür. Bu, yüksek performansa yönelik optimizasyonlara izin verir.</p><p>Ölçeklenebilirliğin önemli bir ölçüt olduğu ve yüksek kullanılabilirliğin kâr elde etmek için esas olduğu yeni veritabanı ekosisteminde, CAP teoreminden bir AP tasarımı tercih edilerek, NoSQL veritabanları daha kolay ölçeklenebilirlik ve daha iyi performans elde etmek için bir çözüm olarak sunuldu. Ancak bu , çoğu NoSQL tasarımında <a href="https://www.allthingsdistributed.com/2008/12/eventually_consistent.html">nihai tutarlılık</a> lehine RDMBS’ler tarafından sunulan güçlü tutarlılık ve işlemsel ACID özelliklerinden vazgeçmek anlamına geliyordu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axeoJ0SvQqe4sPbo6sEiPQ.png" /></figure><p>NoSQL veritabanları, anahtar/değer, belge, geniş sütun veya grafik gibi ilişkisel modelden farklı bir model kullanır. Bu modellerle NoSQL veritabanları normalleştirilmez ve tasarım gereği doğal olarak şemasızdır. NoSQL veritabanlarının çoğu, otomatik parçalamayı destekler ve geliştirici müdahalesi olmadan kolay yatay ölçeklemeye olanak tanır.</p><p><a href="https://www.mongodb.com/scale/when-to-use-nosql-database">NoSQL, nihai tutarlılığın kabul edilebilir olduğu sosyal medya gibi uygulamalar için faydalı olabilir</a> — kullanıcılar, veritabanının tutarlı olmayan bir görünümünü görüp görmediklerini fark etmezler ve veriler, durum güncellemeleri, tweet’ler vb. içerdiğinden, güçlü tutarlılık şart değildir. . Ancak, e-ticaret platformları gibi tutarlılığın kritik olduğu sistemler için NoSQL veritabanlarının kullanımı kolay değildir.</p><p>NewSQL sistemleri, NoSQL’in ölçeklenebilirliğini ve yüksek kullanılabilirliğini ilişkisel model, işlem desteği ve geleneksel RDBMS’lerin SQL’i ile birleştirme arzusundan doğar. <a href="https://cs.brown.edu/~ugur/fits_all.pdf">Herkese uyan tek çözümlerin sonu geldi</a> ve OLTP gibi farklı iş yükleri için özelleştirilmiş veritabanları yükselmeye başladı. Çoğu NewSQL veritabanları, ağırlıklı olarak OLTP veya hibrit iş yüklerine odaklanan eksiksiz bir yeniden tasarımdan doğar.</p><p>Geleneksel RDMBS mimarisi, dağıtılmış bir sistem düşünülerek tasarlanmamıştır. Bunun yerine, ihtiyaç ortaya çıktığında, dağıtılmış tasarımlar için destek, orijinal tasarımın üzerine sonradan düşünülerek inşa edildi. NoSQL’in toplu biçiminden ziyade normalleştirilmiş yapıları nedeniyle, RDBMS’nin hem ölçeği genişletmek hem de tutarlılık gereksinimlerini korumak için karmaşık kavramlar getirmesi gerekiyordu. Yatay ölçeklemeye izin vermek için manuel parçalama ve master-slave mimarileri geliştirildi.</p><p>Bununla birlikte, toplama için farklı düğümler arasında veri taşınmasıyla birleştirmeler daha maliyetli hale geldiğinden ve bakım ek yükü zaman alıcı hale geldiğinden, RDBMS, ölçeklendirme sırasında performansının çoğunu kaybeder. Performansı korumak için karmaşık sistemler ve ürünler geliştirildi — ancak bugün hala geleneksel RDBMS’ler doğal olarak ölçeklenebilir olarak görülmemektedir.</p><p>NewSQL veritabanları, baştan beri dağıtılmış bir mimari göz önünde bulundurularak bulut çağı için oluşturulmuştur.</p><h3>NewSQL çözümlerinde gözlemlenen farklı özellikler nelerdir?</h3><p><strong>Tutarlılık(Consistency):</strong></p><p>Tutarlılığı kullanılabilirliğe tercih eden, CAP’den CP, çoğu <a href="https://dbmsmusings.blogspot.com/2018/09/newsql-database-systems-are-failing-to.html">NewSQL veritabanları, bazı kullanılabilirlikten ödün vererek güçlü tutarlılık sunar</a> . Küresel bir sistemden veya yerel bölüm düzeyinden Paxos veya Raft gibi fikir birliği protokollerini kullanarak bu veritabanları tutarlılık sağlayabilir. <a href="https://www.memsql.com/blog/why-nosql-databases-wrong-tool-for-modern-application/">MemSQL</a> gibi bazı çözümler, farklı kullanım durumlarında farklı konfigürasyonlara izin vererek, tutarlılık ve kullanılabilirlik arasındaki dengeyi ayarlamayı da sunar.</p><p><strong>Ana hafıza(Main memory):</strong></p><p>Geleneksel RDBMS’ler, en yaygın olarak SSD’ler veya HDD’ler olmak üzere veri depolama ortamı olarak ikincil depolamaya veya diske güvenir. OLTP iş yükleri çok fazla veri gerektirmediğinden, geçmiş veriler veri ambarlarında arşivlenebildiğinden ve yalnızca daha güncel bilgilere ihtiyaç duyulduğundan, birkaç NewSQL çözümü depolama olarak ana belleği (RAM) kullanır. Bellek erişimi, disk erişiminden önemli ölçüde, SSD’den neredeyse 100 kat ve HDD’den 10.000 kat daha hızlıdır.</p><p>Bellek içi çözümler, yoğun eşzamanlılık sistemlerini ve özellikle <a href="https://web.stanford.edu/class/cs346/2015/notes/Lecture_One.pdf">arabellek yöneticilerini</a> ortadan kaldıran veya basitleştiren ek performans artışları sunar .</p><p>Tüm veriler (veya çoğu) zaten ana bellekte olduğundan, arabellek yöneticileri geçersiz hale gelir. Eşzamanlılığa gelince, farklı uygulamalarda, örneğin serileştirmede farklı çözümler mevcuttur.</p><p>Peki persistence? RAM’ler doğası gereği değişkendir. Güç kesildiğinde, devam etmesi gereken veriler kaybolabilir. Bellek içi veritabanları, genellikle disklerde seyrek yedekleme kombinasyonları, durumu koruma ve kurtarılabilirlik için günlüğe kaydetme veya kritik veriler için geçici olmayan RAM’ler kullanma gibi farklı şekillerde bunu hafifletir.</p><p>Bellek içi NewSQL çözümlerinin iki ana örneği VoltDB ve MemSQL’dir.Bu yazımda voltDB hakkında bilgi vereceğim. Diğerleri genel olarak aynı yapıyı üzerine inşa edilmişlerdir.(Aralarında kendilerine ait ürettikleri bir çözüm bulunmakta tabiki.)</p><h4>VoltDB</h4><p>VoltDB, bellek içi ACID uyumlu bir ilişkisel veritabanıdır. <a href="http://nms.csail.mit.edu/~stavros/pubs/hstore.pdf">VoltDB’nin mimarisi, Michael Stonebraker ve diğerleri tarafından tasarlanan H-Store’a</a> dayanmaktadır .OLTP iş yükleri için tasarlanmış bir bellek içi veritabanı.VoltDB hızlı verilere odaklanmıştır ve ticaret uygulamaları, çevrimiçi oyunlar, IoT sensörleri <a href="https://www.voltdb.com/solutions/">ve daha fazlası gibi büyük veri akışlarının hızlı bir şekilde işlenmesi gereken belirli uygulamalara hizmet etmek için oluşturulmuştur. </a>OLTP ilkelerine uygun VoltDB, sıfırdan performans gösterecek şekilde tasarlanmıştır.</p><p>VoltDB , yalnızca saklı yordamlara sahip olmanın ve bunları verilere daha yakınlaştırmanın bilinçli kararıyla <a href="https://www.voltdb.com/product/data-architecture/no-wait-design/">serileştirilmiş işlemleri gerçekleştirebilir</a> . Prosedürler atomik işlemlere bölünür ve bu işlemler sırayla serileştirilir ve bir kuyruktan gerçekleştirilir. Bu serileştirilmiş işlem şeması, eşzamanlılık yönetimi için ek yükten kurtularak performansı artırır. VoltDB geçici sorguları da desteklerken, bu saklı yordamlar performans iyileştirmelerinden yararlananlardır. Bu, son kullanıcı geçici sorguları yürütemediğinden OLTP iş yükleriyle uyumludur.</p><p>Bellek içi veritabanları için önemli bir soru ve ACID ilkelerinin gereksinimlerinden biri de dayanıklılıktır. VoltDB, <a href="https://docs.voltdb.com/UsingVoltDB/ChapKSafety.php">anlık görüntüler, komut günlüğü, K güvenliği ve veritabanı çoğaltma dahil olmak üzere</a> çeşitli teknikler aracılığıyla dayanıklılık sağlar . Bu yaklaşımlarla VoltDB, yedeklilik sağlar ve dayanıklı verilere izin verir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*OIrf6Vag6aL39S-brM64IQ.png" /></figure><p>aklınıza sadece VoltDb gelmesin neredeyse bir çok hype servisde şu an kendilerine ait newSQL desteği vermektedir. Bunların sırası listesini aşağıda paylaşıyorum. İçlerindeki en iyi çözümler Google Spanner ile VoltDB gibi geldi ama Amazon Aurora’yı da en kısa sürede denemek istiyorum. VoltDP open source olması da en büyük artılarından biri. Github linki <a href="https://github.com/VoltDB/voltdb"><strong>buraya</strong></a> bırakıyorum.</p><ul><li><a href="https://en.wikipedia.org/wiki/Amazon_Aurora">Amazon Aurora</a></li><li><a href="https://en.wikipedia.org/wiki/Apache_Trafodion">Apache Trafodion</a></li><li><a href="https://en.wikipedia.org/wiki/Clustrix">Clustrix</a></li><li><a href="https://en.wikipedia.org/wiki/CockroachDB">CockroachDB</a></li><li><a href="https://en.wikipedia.org/wiki/Google_Spanner">Google Spanner</a></li><li><a href="https://en.wikipedia.org/wiki/NuoDB">NuoDB</a></li><li><a href="https://en.wikipedia.org/wiki/Pivotal_GemFire">Pivotal GemFire</a> XD</li><li><a href="https://en.wikipedia.org/wiki/SingleStore">SingleStore</a> was formerly known as MemSQL.</li><li><a href="https://en.wikipedia.org/wiki/TIBCO_Software#Products">TIBCO Active Spaces</a></li><li><a href="https://en.wikipedia.org/wiki/TiDB">TiDB</a></li><li><a href="https://en.wikipedia.org/wiki/TokuDB">TokuDB</a></li><li><a href="https://en.wikipedia.org/wiki/TransLattice">TransLattice</a> Elastic Database</li><li><a href="https://en.wikipedia.org/wiki/VoltDB">VoltDB</a></li><li><a href="https://en.wikipedia.org/wiki/YugabyteDB">YugabyteDB</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae5de2cc302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Derinlemesine gRPC incelemesi…]]></title>
            <link>https://cedellalahmet.medium.com/derinlemesine-grpc-incelemesi-cb8eb0bb5887?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb8eb0bb5887</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 14:14:53 GMT</pubDate>
            <atom:updated>2022-03-21T15:11:26.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6ufkIOzURh0WBg_q9jrSgQ.png" /></figure><p><strong>Özet</strong>:<br>Bu yazımızda derinlemesine gRPC inceleyip neden ortaya çıktığını, RESTFul API’s ile ne gibi farkları olduğunu, REST’e göre artıları ve eksilerini tartışıp, JSON representation(temsil)’unun ne gibi artıları ve eksileri olduğunu ve bunları belirttikten sonra, mikro servislerde internal haberleşmede gRPC kullanmanın getirdiği artılardan ve basitlikten bahsettikten sonra örnek uygulamalar ile tamamlamayı düşünüyorum. Her zaman olduğu gibi en net kaynaklar her zaman anlatılan teknolojilerin dökümanları olmakta birlikte benim anlatacaklarımda bu dökümanların üzerine deneyim ile elde edilmiş bilgileri eklemek ve anlatmak olacaktır.</p><p><strong>gRPC Nedir ?</strong></p><p>Aslında gRPC gecmeden önce REST’den teorik olarak bahsetmek gerekiyor. Çünkü bir bakıma REST’in eksik ya da tam performanslı olmayan bazı özelliklerinden dolayı RPC dediğimiz kavram ortaya çıktı denilebilir.</p><p><strong>Not: Bu yazıdımızda REST den sadece teorik olarak bahsedeceğim.</strong></p><p>REST’in tanımına baktığımız zaman. Http üzerinden belirli verb’lere(GET/POST vs) anlam yükleyerek objeleri backend tarafında yönetmek için API’lar diyebiliriz. Özünde baktığınız zaman bu tanım tek başına bir şey ifade etmiyor olabilir.</p><p>REST’in bir diğer tanımı “kolay anlaşılması ”. misal Curl, Postman, Swagger gibi toollar ile kullanıcının okuyabileceği bir data elde edebiliyorsunuz.</p><p>Bir diğer özelliği Http1.1 üzerine kurulmuş bir sistem. Http’nin sahip olduğu tüm verb’ler REST üzerinde mükemmel uyum ile çalışıyor. Örnek REST kullanmış olduğu verb ile alabileceği <strong>unauthorized</strong> gibi durumları anlamlı bir şekilde okuyabilirsiniz.</p><pre>HTTP/1.1 401 Unauthorized<br>Date: Wed, 18 Marc202 07:28:00 GMT<br>WWW-Authenticate: Basic realm=&quot;Access to staging site&quot;</pre><p>REST kullanınca bir coupling ortaya çıkmıyor(Tamamen değil). Şöyle ki</p><pre>{<br>&quot;value&quot; : 1213.2131231<br>}</pre><p>Yukarıdaki JSON inceleyelim client dan çıkan bu data server’a gitmeden önce value değerinin server icin bir anlam ifade etmiyor. server bunun double, float olduğuna bakmaz ve gelen data onun için her zaman String tipindedir isterse kendi içerisinde cast ya da modellemelerle bu veriyi kendi istediği veri tipine convert edebilir. Bu da bize aslında de-coupling sağlıyor. Veri tipine bağımlılığı ortadan kaldırıyor.(Aslında hem iyi hem de kötü bir çözüm ileride daha net acıklayacağım bu durumu)</p><p>Şimdiye kadar her şey REST’i överek ilerledik peki sorun neydi, problem neydi de ortaya RPC dediğimiz kavram ortaya çıktı. Aslında cevap çok basit <strong>HIZ(Tek etmen değil tabiki ama önemli bir durum).</strong></p><p>Hız, tüm yazılım dünyasının çözülmeyen, ya da çözülmesi günümüzde bile mümkün olmayan sorunu, yazılım şirketleri bunun için her zaman kendi çözümlerini üretmeye çalışıyor. Ve çözümler ile tam çözemese bile HIZ puzzle ında birer parca ekleyerek en iyi yöntemi oluşturmaya çalışıyorlar. Bununla birlikte Hızlı bir teknoloji üretirken bu teknolojinin diğer teknolojilerle birlikte çalışabilmesi gerekiyor. Yani hızlı bir teknoloji üreteceğim derken sadece tek bir ortamda çalışan bir teknoloji ürettim diyemezseniz. Buradan uyumluluk ve uygunluk dediğimiz iki prensibin önemi ortaya çıkıyor vs.</p><p>Peki REST hız problemi neydi. Http1.1 üzerinde çalışıyor olmasından dolayı yüksek performans beklediğini yerlerde ya da dışarıya bir şey expose etmeyeceğim yani kendi içinde(internal) (mikro servisler gibi ) kullanacağım dediğiniz zaman bir önemi kalmıyor. Sebebi iç servislerde gecikme(latency) çok az zaman olmalı vs. Böyle durumlarda yapılması gereken http2.0 kullanan çözümler üretmek gerekiyor.</p><p><strong>Not : Kısaca Http 1.1 vs Http 2.0</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vJ2ppTQTAeTUFC3lavrbEA.png" /></figure><p><strong>HTTP/1.1 ile HTTP/2 protokolleri arasındaki en büyük fark</strong>, HTTP/1.1 protokolünün her statik dosya için (css,js,resim,video vb.) ayrı istekler göndermesidir. Her dosya için tek tek istek gönderilmesi ve yanıtlanması açılma süresinin artmasına neden olur. <strong>HTTP/2 de ise gelen istekler toplu olarak alınarak, en hızlı şekilde yanıtlanmakta ve bu sayede açılış hızlarında ki gecikmelerin önüne geçilmektedir.</strong></p><p>HTTP/2 ile birlikte sunucular üzerindeki yükün en aza indirilmesi hem son kullanıcı bazlı hemde hizmet sağlayıcı firmalar tarafından büyük bir yükü almış oldu. HTTP/2 çoklu bağlantı yapısı ile bilikte TCP üzerinden birden fazla istek gönderebilmekte. Her bir çağrı için ayrı bir istek açılması ve tek tek yanıtlanması yerine tek bir istekte tüm çağrıların iletilmesi ve karşı sunucunun cevaplamasını sağlıyor, bu özellik de <strong>sitenizde herhangi bir optimizasyon yapmasanız dahi HTTP/2 protokolü sayesinde web sitenizin daha hızlı yüklenmesini sağlamaktadır.</strong></p><p>Son olarak<strong> HTTP/2 </strong>‘yi birkaç kelime ile açıklamak gerekirse, web sayfalarının daha hızlı yüklenmesini sağlar ve tüm kullanıcılar için zaman kaybını önler. Yapılan birçok testte <strong>açılış hızında %20’lik bir artış</strong> gözükmekte olup, <strong>optimize edilmiş web sayfalarında bu oran %30–40’lık açılış hızı </strong>farkına ulaşmaktadır.</p><p>Genel olarak sistemimiz aşağıdaki isterleri barındırıyorsa, REST ile devam etmekte herhangi bir problem bulunmamakta.</p><ul><li>Web’de, tüm web sayfalarının HTTP konuşmasından, kendilerini bir GET ile göstermesinden ve GET veya POST ile formları işlemesinden memnunuz [Uniform Interface]</li><li>Web’de, tarayıcımızın yüzlerce içerik türünü (HTML, resimler, CSS, yazı tipleri, Javascript, RSS…) anlamasından ve bunları çok sayıda yerleşik kurala (önbelleğe alma, görüntüleme, güvenlik…) göre işlemesinden mutluyuz. Kendinden Tanımlayıcı Mesajlar]</li><li>Web’de, yükleme süresini hızlandırmaya ve trafik artışlarını (“Slashdot efektleri” gibi) emmeye yardımcı olan tarayıcı içi önbelleğe alma, içerik dağıtım ağları ve diğer paylaşılan önbellek biçimlerine sahip olmaktan mutluyuz. Web sayfalarının garip davranışlarını düzeltmek için bazen hızlı bir ctrl+F5 gerekli olsa da. [Katmanlı Sistem ve Önbelleğe Alma]</li><li>Web’de, proxy’lerin ve güvenlik duvarlarının web protokollerini anlamasından ve şüpheli TCP/UDP bağlantılarını engellerken bunların akmasına izin vermesinden memnunuz. [Görünürlük]</li><li>Web’de, tarayıcıların kendi başlarına sağlanan HTML’ye dinamiklerin nasıl ekleneceğine dair hiçbir fikri olmadığından, komut dosyalarının her sayfa için sunucu tarafından teslim edilebilmesinden memnunuz [İsteğe Bağlı Kod]</li></ul><p>Gelelim RPC’ye;</p><ul><li>Siz (büyük olasılıkla) isteğe bağlı kod istemiyorsunuz. Müşterilerinizin özelliklerinizi okumasını ve API’nizi tam olarak sizin (ve onların) istediğiniz gibi aramasını istiyorsunuz.</li><li>Siz (büyük olasılıkla) ağ düzeyinde görünürlük istemiyorsunuz. Aksine, mümkün olduğunca çok TLS şifrelemesi istiyorsunuz.</li><li>Siz (büyük olasılıkla) paylaşılan önbellekleri veya istemci tarafı önbelleğe almayı istemezsiniz. Aksine, uzak önbellekler en kötü düşmanlarınız arasındadır. API tüketicileriniz tarayıcı değilse, genellikle önbelleğe alma başlıklarını yine de yok sayarlar.</li><li>Siz (muhtemelen) içerik müzakeresi olmadan yapabilirsiniz ve diğer HTTP özellikleri aşağı yukarı REST en iyi uygulamalarıyla birlikte sunulur (biliyorsunuz, Temsil ve Kaynağa karşı). Her güncel dil, Xml ve Json gibi biçimleri anlayabilir.</li><li>Siz (büyük olasılıkla) CRUD işlemleri için Kaynakları açığa çıkarmak ve uygulamalarınızdaki gerçek işlemleri tetiklemek için bu garip ortadaki adamları kullanmak istemiyorsunuz.</li></ul><p>Tüm (muhtemelen) istediğiniz, bir dizi sunucu tarafı işlevlerinizi uzak tarayıcılara veya sunuculara maruz bırakmaktır. Hızlı, zarif, sağlam bir şekilde.</p><p><strong>API’niz (büyük olasılıkla) “RPC” diye bağırıyor. Bu durum REST mimari tarzı sizin isterlerinize tam olarak cevap veremeyebilir.</strong></p><p>Elbette, HTTP’nin şu veya bu özelliğine ihtiyacınız olabilir. Örneğin, tarayıcı tarafında önbelleğe almadan yararlanmak için Ajax kaynaklı salt okunur işlemleriniz için GET yöntemini ve farklı URI’leri kullanmak isteyebilirsiniz. Veya genel uygulamalardan (JsonAPI protokolü için Aktif Kayıt stili istemciler gibi) yararlanmak için veritabanınızı HTTP üzerinden CRUD olarak göstermek isteyebilirsiniz.</p><p>Ama ihtiyaçlarınız ne olursa olsun, <em>hayat kısa</em> . REST kısıtlamaları gibi soyut bir “kurallar kümesinden” başlamanız gerekmez. Gerçekten sahip olduğunuz ihtiyaçlara uygun, <strong>anahtar teslimi bir protokol arasanız</strong> iyi olur.</p><p>Hafif RPC, CRUD, pub/sub, iş kuyrukları, uzak dosya sistemleri, veri sorgulama/filtreleme, yüksek performanslı bilgi işlem ve çift yönlü mesajlaşma için bu tür tonlarca çözüm (çoğunlukla RESTful olmayan) vardır. Nadiren yenilik yapmanız, bir protokole yeni yetenekler eklemeniz veya hibrit yaklaşımlar kullanmanız gerekir. Ancak “fiilleri isme çevirmeye” başlamak veya dogma olarak soyut ilkeleri takip etmek, yapmanız gereken son şeydir.</p><p><strong>RPC(Remote Procedure Call) Uzak sunucudaki metotları sanki kendi oramının birer parçasıymış gibi çağırabilen sistemdir.</strong></p><ul><li>gRPC transport/iletişim/veri iletimi için http/2 protokolünü kullanmaktadır.</li><li>TCP socket haberleşmesi sağlayabilmektedir.</li><li>Http 2 sayesinde binary serialization kullanmaktadır. Böylece text-based mesajlaşmaya nazaran oldukça hızlıdır.</li><li>Aynı bağlantı üzerinden birden fazla paralel request desteği sağlamaktadır. Http 1.0&#39;da ise bir request’e nazaran bir response söz konusudur.</li><li>Client ile server arasında çift yönlü iletişim vardır.</li></ul><p>Şimdi bildiğiniz gibi yapılandırılmış verileri seri hale getirmek için biz REST de XML,JSON, YML gibi serileştirmeleri kullanıyoruz fakat RPC de biz bunun için protopuff yada proto kullanılıyor artları eksilerini uzun uzadıya yazmak yerine aşağıdaki şema ile daha güzel anlaşılacağını düşünüyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpAWwFP7okNwSM3JWJ97fA.png" /></figure><p><strong>Protobuf veya Proto:</strong></p><p>Google protobuf veya proto, yalnızca yapılandırılmış verileri seri hale getirmek için bir mekanizmadır. Proto daha küçük, daha basit, daha hızlı ve dilden bağımsız. Bunu JSON veya XML’e benzetebilirisiniz ancak ona kıyasla daha küçük ve daha hızlı görebilirsiniz.</p><ul><li><strong>dilden bağımsız</strong></li><li><strong>Makine Tarafından Okunabilir:</strong> Protobuf, tarayıcılar üzerinden değil, hizmetler arasında mesaj alışverişi yapmak için kullanılabilir, çünkü proto’lar ikili veya makine tarafından okunabilir ve insan tarafından okunamaz.</li><li><strong>Jeneratörlerin Serileştirmesini veya Serileştirmesini Sağlar</strong> : Protobuf, protobuf derleyicisi (protoc olarak adlandırın) ile kaynak koduna kolayca derlenebilir (Şu anda JAVA, Objective c, python, c#, ruby, go , java nano, c++ 8 farklı dili desteklemektedir) ve hangi serileştirme veya seri kaldırma daha kolaydır ve elle ayrıştırmaya gerek yoktur.</li><li><strong>Türleri ve Doğrulamaları</strong> destekler : json’dan farklı olarak, .proto dosyasında alan türleri belirleyebilir ve bunlar için doğrulamalar ekleyebiliriz.</li><li><strong>Lesser Boilerplate code</strong> : Türleri desteklediğinden ve kaynak kodu oluşturuculara sahip olduğundan, çok fazla ortak kod yazmamıza veya yanıtı elle ayrıştırmamıza gerek yok. <strong>RPC Arayüzlerini Destekler</strong> : Mesaj türlerinizi bir RPC (Uzaktan Prosedür Çağrısı) sistemi ile kullanmak istiyorsanız, bir proto dosyasında bir RPC servis arayüzü tanımlayabilirsiniz ve protokol tampon derleyicisi seçtiğiniz dilde servis arayüz kodu ve taslakları oluşturacaktır.</li></ul><p><strong>gRPC ile basit bir İstemci Sunucu Mimarisi</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*RyuxRjHSslCA0XD3N0H6wg.png" /></figure><ul><li>Bir istemci uygulaması, sunucuya iletilecek parametreleri içeren istemci saplamasına yerel bir prosedür çağrısı yapar. Sunucu çalışma zamanı kitaplığı isteği alır ve iletilen parametreleri sıraya koyan (paketten çıkaran) ve gerçek parametreleri çağıran sunucu saplama prosedürünü çağırır. prosedür.</li><li>İstemci saplaması, parametreleri, sıralama adı verilen bir işlem aracılığıyla serileştirir, isteği yerel bilgisayardaki yerel istemci-zaman kitaplığına iletir ve bu da isteği sunucu saplamasına iletir.</li><li>Sunucu saplaması, istemci saplamasına aynı şekilde, istemcinin normal yürütmeye devam ettiği bir noktada bir yanıt gönderir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqgRJKoXZJ9WNnesNJoAVg.png" /></figure><p>gRPC, yukarıdakine benzer şekilde çalışan açık kaynaklı bir çerçevedir ve dilden bağımsızdır.. Bu, node.js, JAVA ve Go’dan gelen istemci çağrılarını işleyen Java ile yazılmış bir grpc sunucunuz olabileceği anlamına gelir. Varsayılan olarak, gRPC, yapılandırılmış verileri sıralamak/düzeltmek için Protokol Tamponlarını uygular ve bunun yanı sıra, avantajlarından biri olan çağrılabilir yöntemler için parametreleri ve geri dönüş yanıtlarını tanımlar.</p><p>gRPC ile bir sunucu ve istemci oluşturmak çok basittir ve aşağıdaki adımlar</p><ul><li>Protokol Arabelleği (.proto) dosyasında hizmet tanımını ve yük yapısını oluşturun.</li><li>protoc kullanarak derleyerek .proto dosyasından gRPC kodunu oluşturun</li><li>Sunucuyu desteklenen dillerden birinde uygulayın.</li><li>Saplama aracılığıyla hizmeti çağıran istemciyi oluşturun.</li><li>Sunucuyu ve istemcileri çalıştırın.</li></ul><p>Bu nedenle, gRPC’nin avantaj ve dezavantajlarının özeti aşağıdaki gibidir.</p><p><strong>gRPC’nin avantajları</strong></p><ul><li><strong>Güvenlik ile birlikte</strong> yüksek performans : gRPC, google protobuf ve http/2 protokolü ile çoklanmış, tek tcp bağlantısı olan, verileri ikili olarak taşıyan, çift yönlü akışa olanak sağlayan vb. ile yüksek performanstır.</li><li><strong>Dubleks akış :</strong> İstemci tarafı ve hizmet akışına aynı anda izin verir.</li><li><strong>Birinci Sınıf Yük Dengeleme:</strong> gRPC, trafiğin hangi arka uca gönderileceğini akıllıca seçebileceği yerleşik bir kitaplık özelliğine sahiptir.</li><li><strong>Seçici mesaj sıkıştırma</strong> : Tek bir akış (veya gerçekten herhangi bir karışık sıkıştırılabilir içerik) üzerinden karışık metin ve resim akışı yapıyorsanız, resimler için sıkıştırmayı kapatabilirsiniz.</li><li><strong>Otomatik oluşturulan istemci kodu:</strong> Protokol ile istemci kodunu ve sunucu kodunu kolayca oluşturabiliriz.</li><li><strong>Büyük ölçüde optimize edilmiş:</strong> gRPC kitaplığı, hız gerilemelerinin olmamasını sağlamak için sürekli <a href="https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5636470266134528">karşılaştırmalar</a> altındadır .</li><li><strong>Bağlantı Havuzu</strong> : Durumları bağlı veya boşta olan yönetilen kanallar üzerinden sunucuya kalıcı bağlantı içeren bağlantı havuzu oluşturabiliriz.</li></ul><p><strong>gRPC’nin Ağrı Noktaları</strong></p><ul><li>Tarayıcılar için destek yoktur, bu nedenle harici hizmetler için kullanılamaz.</li><li>Hiçbir url bitiş noktası bu nedenle yanıtı kontrol etmek için postacı veya curl ile test edilemez.</li><li>Önceden tanımlanmış hiçbir durum kodu ve özel durum kodu oluşturma, çakışmalarla sonuçlanabilir.</li></ul><p>Ayrıca, aşağıdaki durumlar için gRPC kullanmanızı öneririm</p><ul><li>Mikro hizmetler yalnızca dahili olduğunda ve bir sunucunun diğeriyle konuşması gerektiğinde.</li><li>Dahili hizmetleriniz yüksek veri yüküyle çift yönlü akış gerektirdiğinde.</li><li>İstemci kitaplıkları yazmak istemiyorsanız.</li></ul><p>Bununla birlikte REST ve gRPC ile yapılan tartışmalarla ile ilgili onlarca konu bulabiliriz(Multiple Connection, duplex vs ) fakat REST ve gRPC kullanımı genel olarak yazılımınızda ki isterlere göre karar verilmesi gerekiyor çünkü iki teknolojininde kendilerine göre artıları ve eksileri bulunmakta ve bu tercihler ise ben görüşüme göre deneyimlerle elde edilebiliyor.</p><p>Yazımızda genel olarak gRPC vs REST kavramından bahsetmeye çalıştım. Şimdi bunu basit iki uygulama ile taçlandıralım.</p><p>İlk önce proto dosyamızı create edelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cd75355692fdc6abae37bcf6304bc7c/href">https://medium.com/media/6cd75355692fdc6abae37bcf6304bc7c/href</a></iframe><p>proto dosyası bizim hizmetimizde ihtiyaç duyduğumuz her şeyi tanımlamak için kullanılır. Yukarıdaki Time objesi bizim verimiz ve bunu tanımlama için proto içerisinde String tipinde tanımlayarak kullanıyoruz.</p><p>TimeService ile biz api’mız olduğunu söylüyoruz ve içerisinde iki tane metod olduğunu söylüyoruz.</p><p>daha sonra terminal ekranında aşağıdaki komutu çalıştırmasını sağlayarak bizim için bir tane grpc için pb dosyasını oluşturmasını sağlıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b71f0287dfaf7e5968a632cbc8149c5/href">https://medium.com/media/1b71f0287dfaf7e5968a632cbc8149c5/href</a></iframe><p>Daha sonra aşağıdaki gibi main.go ile bir server oluşturalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be2f64f1b073c2a39f4ecf806bd46cff/href">https://medium.com/media/be2f64f1b073c2a39f4ecf806bd46cff/href</a></iframe><p>Artık server tarafımız hazır. Bundan sonraki adımda ise client oluşturalım. Bunun için python da bir uygulama yazmamız gerekecek.</p><p>Ilk önce python da yazacağımız client için aşağıdaki komut satırını çalıştıralım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb75241056fc263a81726c6bc8621d95/href">https://medium.com/media/cb75241056fc263a81726c6bc8621d95/href</a></iframe><p>Daha sonra aşağıdaki gibi bir server oluşturalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fff7ba7c6d3abcfa03e75075658b0cd/href">https://medium.com/media/5fff7ba7c6d3abcfa03e75075658b0cd/href</a></iframe><p>Çok basit seviyede client ile server oluşturduktan sonra run edip aşağıdakine benzer bir görüntü elde ediyorsak gRPC ile çok basit bir API haberleşmesi sağlamış oluyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RD7MleSRoa8kBwPJZoi5oQ.png" /></figure><p>Kaynaklar…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKJ4dhwBoVlE%3Fstart%3D806%26feature%3Doembed%26start%3D806&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKJ4dhwBoVlE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKJ4dhwBoVlE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/82bc0ca5f0fa19cbc930127cf45a840a/href">https://medium.com/media/82bc0ca5f0fa19cbc930127cf45a840a/href</a></iframe><p><a href="https://grpc.io/#:~:text=gRPC%20is%20a%20modern%20open,tracing%2C%20health%20checking%20and%20authentication">https://grpc.io/#:~:text=gRPC%20is%20a%20modern%20open,tracing%2C%20health%20checking%20and%20authentication</a>.</p><p><a href="https://ahmet.im/">https://ahmet.im/</a></p><p><a href="https://cloud.google.com/blog/products/api-management/understanding-grpc-openapi-and-rest-and-when-to-use-them">gRPC vs REST: Understanding gRPC, OpenAPI and REST and when to use them in API design | Google Cloud Blog</a></p><p><a href="https://www.google.com/search?q=what+is+this+grpc&amp;rlz=1C5CHFA_enTR995TR995&amp;ei=Yoc4YqaRK5OKxc8PtPeUsAY&amp;ved=0ahUKEwimysf-sNf2AhUTRfEDHbQ7BWYQ4dUDCA4&amp;uact=5&amp;oq=what+is+this+grpc&amp;gs_lcp=Cgdnd3Mtd2l6EAMyCAghEBYQHRAeMggIIRAWEB0QHjIICCEQFhAdEB4yCAghEBYQHRAeMggIIRAWEB0QHjIICCEQFhAdEB4yCAghEBYQHRAeMggIIRAWEB0QHjIICCEQFhAdEB4yCAghEBYQHRAeOgQIABBDOgUIABCRAjoFCAAQgAQ6CwguEIAEEMcBENEDOgUILhCABDoLCC4QgAQQxwEQowI6CAguEIAEENQCOgcIABCABBAKOgQIABANOgYIABANEAo6BggAEBYQHjoICAAQFhAKEB5KBAhBGABKBAhGGABQAFi0JWCSJ2gBcAB4AIABnQGIAaoUkgEEMC4yMpgBAKABAbABAMABAQ&amp;sclient=gws-wiz">Search link :)</a></p><p><a href="https://github.com/ahmetdellall/grpc-examples.git">Örnek projenin Github linki</a> :</p><p><a href="https://github.com/ahmetdellall/grpc-examples">https://github.com/ahmetdellall/grpc-examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb8eb0bb5887" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka nedir ?]]></title>
            <link>https://cedellalahmet.medium.com/apache-kafka-nedir-a8e1e5dc211e?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e1e5dc211e</guid>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 15:49:39 GMT</pubDate>
            <atom:updated>2022-03-08T15:49:39.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka Nedir ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccUPUFBXUzP5mt6uYEoQtg.png" /></figure><p>Apache Kafka nedir ? sorusuna genelde aldığımız cevap “gerçek zamanlı olarak akış verilerini almak ve işlemek için optimize edilmiş, dağıtılmış bir veri deposudur.” Bir farklı ifade şeklide genelde “ Kafka’nın bir mesaj kuyruğu olduğudur.”. Aslında özünde hepsi doğrudur. Çünkü kullanım itibari bahsedilen özelliklerin tümünü destekler. Fakat Kafka yukarıdaki özelliklerin yanında kendine ait eşsiz özellikleri barındırdığıdır.</p><p>Bu yazımızda Apache Kafkayı derinlemesine inceleyip, basitten zor’a doğru bir maceraya cıkacağız.</p><p>Kafkayı eşsiz kılan özelliklere bakalım önce;</p><ul><li>Saniyede milyonlarca mesajı işlemek için <strong>ölçeklenebilir bir gerçek zamanlı mesajlaşma platformu.</strong></li><li>Büyük hacimli <strong>büyük veri analitiği</strong> ve küçük hacimli <strong>işlemsel veri işleme</strong> için bir <strong>olay akış platformu</strong> .</li><li><strong>Dağıtılmış bir depolama</strong> , geri basınç yönetimi, çeşitli iletişim protokollerinin desteklenmesi ve olayların garantili sıralama ile yeniden oynatılabilirliği için gerçek bir ayrıştırma sağlar.</li><li>ETL akışı için bir <strong>veri entegrasyon</strong> çerçevesi.</li><li>Sürekli durum bilgisi olmayan veya durum bilgisi olan akış işleme için bir <strong>veri işleme</strong> çerçevesi.</li></ul><p>Kafka yukarıdaki özelliklerin hepsini içerisinde barındıran ve bu <strong>özelliklerin tek bir platformda birleşimi Kafka’yı benzersiz</strong> (ve başarılı) kılar.</p><p>Peki Kafka ne değildir ?</p><ul><li><strong>Milyonlarca istemci için</strong> bir proxy (mobil uygulamalar gibi) — ancak bazı kullanım durumları için Kafka’ya özgü proxy’ler (REST veya MQTT gibi) mevcuttur.</li><li>Bir <strong>API Yönetim</strong> platformu — ancak bu araçlar genellikle tamamlayıcıdır ve Kafka API’lerinin oluşturulması, yaşam döngüsü yönetimi çevrilmesi için kullanılır.</li><li>Karmaşık sorgular ve toplu analiz iş yükleri için bir <strong>veritabanı</strong> — ancak işlem sorguları ve nispeten basit toplamalar için yeterince iyi (özellikle ksqlDB ile).</li><li>Cihaz yönetimi gibi özelliklere sahip bir <strong>IoT platformu</strong> — ancak MQTT veya OPC-UA gibi (bazı) IoT protokolleriyle doğrudan Kafka’ya özgü entegrasyon mümkündür ve (bazı) kullanım durumları için uygun yaklaşım.</li><li>Güvenlik açısından kritik veya belirleyici sistemler gibi <strong>zorlu gerçek zamanlı uygulamalar için</strong> bir teknoloji — ancak bu, diğer tüm BT çerçeveleri için de geçerlidir. Gömülü sistemler farklı bir yazılımdır!</li></ul><p>Bu nedenlerle <strong>Kafka, bu diğer teknolojilerin rekabetçi değil tamamlayıcısıdır</strong> .</p><p>Gerçek zamanlı örneklerle bu konuyu biraz acalım. Örnek olarak büyük hacimli verileri gerçek zamanlı olarak işlemek, Kafka’nın kritik yeteneklerinden biridir. Peki bu önemli yetenek hangi şirket/şirketler tarafından kullanılıyor dersek aklımıza Tesla gelebilir.</p><p><strong>Tesla sadece bir araba üreticisi değil. Tesla, birçok yenilikçi ve son teknoloji yazılım yazan bir teknoloji şirketidir</strong> . Tesla Supercharger’ları ile otomobiller için bir enerji altyapısı, Gigafactory’lerinde güneş enerjisi üretimi ve çok daha fazlasını sağlıyorlar. <strong>Araçlarından, akıllı şebekelerinden ve fabrikalarından gelen verileri işlemek ve analiz etmek ve</strong> diğer BT arka uç hizmetleriyle gerçek zamanlı olarak entegre etmek, başarılarının çok önemli bir parçasıdır.</p><p>Tesla, “Günde milyonlarca cihazı ve trilyonlarca veri noktasını desteklemek için” <a href="https://www.confluent.io/blog/stream-processing-iot-data-best-practices-and-techniques/">Kafka tabanlı bir veri platformu altyapısı kurdu . </a>Tesla , 2019&#39;da bir Kafka Zirvesi’nde <a href="https://www.confluent.io/kafka-summit-san-francisco-2019/0-60-teslas-streaming-data-platform/">Kafka kullanımının heyecan verici bir tarihini ve gelişimini gösterdi</a>. Buradaki serüveni izlemek için bağlantılı linklere tıklanarak ilerlenebilir.</p><p>Bunun gibi örneklerin sayısını arttırabiliriz. Fakat özünde dikkat çekmenizi istediğim nokta Kafka’nın artık büyük teknoloji şirklerinin merkezinde yer aldığı ve kendini sürekli olarak geliştirdiğidir.</p><p>Şimdi Kafka hakkında bir izlenime kavuştuktan sonra bileşenlerine örnekler ile giriş yapabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QqLTumYuNrpmNoZr1QoEA.png" /></figure><p>Yukarıdaki resimde görebildiğiniz gibi Apache Kafka’nın bileşenleri resmedilmiştir. Şimdi bu bileşenleri ayrıntılı inceleyelim.</p><p><strong>Producer :</strong></p><p>Apache Kafka’nın toplayacağı verileri gönderen bileşen. Buradaki veri her şey olabilir.</p><ul><li>Video upload sırasındaki yüklenen video olabilir.</li><li>Log kaynağı olabilir.</li><li>Sisteminizde ki kullandığınız event olabilir.</li></ul><p>Temel olarak, veri akışının kaynağı olan bir uygulama, <strong>Producer</strong> dediğimiz bileşendir. mesajlar veya tokenlar oluşturmak ve bunları Kafka clusterdaki bir veya daha fazla topic’e yayınlamak için Apache Kafka Producer’ı kullanıyoruz.</p><p>Ayrıca, Kafka’nın Producer API’si, mesajın veya token’in paketlenmesine ve Kafka Sunucusuna teslim edilmesine yardımcı olur.</p><p>Ayrıntılı şekilde inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*WxOQVoC6id87DujowID9sg.png" /></figure><h3>Kafka Producer’ın Bileşenleri</h3><p>Yukarıdaki şekli incelediğimiz zaman karşımıza çıkan bileşenkler;</p><p><strong><em>Send()</em></strong><em> — Kaydı, gönderilmek üzere bekleyen kayıtların ara belleğine ekler ve hemen döner. Bekleyen kayıtlardan oluşan bu arabellek, verimlilik için bireysel kayıtları bir araya getirmeye yardımcı olur.</em></p><p><strong><em>Serializer — </em></strong><em>Kullanıcının ProducerRecord ile sağladığı key ve value nesnelerini bayt olarak serileştirmeye yardımcı olur.</em></p><p><strong><em>Partitioner</em></strong><em> — Her ProducerRecord’a bölüm ataması Partitioner tarafından yapılır. İki tür bölümleme stratejisi vardır :</em></p><ul><li><em>Round Robin Partitioning- Bu, ProducerRecord da anahtar Null olduğunda kullanılır. Bölmeler Round Robin tarzında atanır.</em></li><li><em>Hash Key-based Partitioning- Bu, ProducerRecord’un bir anahtarı olduğunda kullanılır. Bölümler, belirli bir key/value için anahtarın karma değerine göre belirlenir.</em></li></ul><p><strong><em>Buffer</em></strong><em> — Gönderilmemiş kayıtların bir bellek arabelleği, producer tarafından her bölüm için tutulur. Ara belleğin boyutu, toplu batch.size yapılandırması tarafından ayarlanabilir.</em></p><p><strong><em>I/O Threads</em></strong><em>- arabellekteki kayıtları isteklere dönüştürmekten ve bunları Kafka broker’a iletmekten sorumludur.</em></p><p>Peki bu bileşenler bir arada nasıl çalışır. Kısaca acıklayayım.</p><p>Kafka brokerlara mesaj gönderme süreci topic adı <em>ve mesaj değerine sahip bir ProducerRecord oluşturmakla başlar. İleti anahtarı ve/veya bir partition da ProducerRecord’da belirtilebilir. ProducerRecord daha sonra send() kullanılarak gönderilir. Daha sonra ProducerRecord, key ve value değerleri ile ağ üzerinden seyahat etmek/gönderilmek üzere ByteArrays’e serileştirildiği serileştiriciye ulaşır.</em></p><p><em>Partitionlar ProducerRecord’da belirtilirse, partitioner aynısını döndürür, aksi takdirde partition stratejisine (Round Robin, Hash Key veya Custom Partitioning) dayalı olarak mesaj değeri için bir bölüm seçer.</em></p><p><em>Bir partition belirlendiğinde, producer , aynı konu ve bölüme gönderilecek olan bir toplu kayıtlara mesaj değerini ekler. Bu gönderilmemiş kayıt yığını ara bellekte tutulur. Mesaj ara belleğe ulaştığında, send() geri döner ve bir sonraki ProducerRecord’u işlemeye başlar.</em></p><p><em>Bu kayıt gruplarını Kafka Broker’a istek olarak göndermekten ayrı bir I/O thread sorumludur. Broker iletileri başarıyla aldığında, yanıt olarak bir RecordMetadata nesnesi döndürür ve bölüm içindeki kaydın topic bilgisine, partition’a ve offset’ine sahiptir.</em></p><p><em>Mesaj Broker tarafından alınamazsa, yanıt olarak bir hata döndürür ve producer, hatayı döndürmeden önce mesajı birkaç kez daha göndermeyi deneyebilir (yeniden deneme sayısı).</em></p><h3>Bazı önemli üretici konfigürasyonlarını analiz edelim</h3><p><strong><em>Acks</em></strong><em> — Producer’ın, bir talebi tamamlamadan önce liderin almasını istediği onay sayısı. Aşağıdaki ayarlara izin verilir:</em></p><ul><li><strong><em>acks = 0</em></strong><em> -&gt; Producer, brokerdan herhangi bir onay beklemeyecektir. Mesajlar ara belleğe eklenecek ve gönderilmiş olarak kabul edilecektir. Mesajın broker tarafından alındığına dair hiçbir güvence verilemez.</em></li><li><strong><em>acks = 1</em></strong><em> -&gt; Producer, yalnızca lider brokerdan onay bekleyecektir. Mesajın takipçi borker tarafından alındığına veya mesajın düzgün bir şekilde kopyalandığına dair hiçbir garanti verilemez.</em></li><li><strong><em>acks = all</em></strong><em> -&gt; Producer, tam set senkronize kopyalardan (liderler + takipçiler) onay bekleyecektir. Bu, kaydın tüm eşitlenmiş aracılar tarafından alındığını ve en az bir eşitleme içi çoğaltma aracısı canlı kaldığı sürece iletinin kaybolmayacağını garanti eder.</em></li></ul><p>Bunlarla birlikte onlarca method’u barındıran Producer API incelemek isterseniz.<a href="https://kafka.apache.org/27/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html"> Bu link’e tıklayabilirsiniz.</a></p><p><strong>Topic</strong></p><p>Basit bir şekilde ifade etmek gerekirse bizim veri depomuz. Daha başka bir ifade ile Producer tarafından gönderdiğimiz verileri depolayan birim/birimlerdir. Kafka topic, mesajları ve olayları <strong>mantıksal</strong> bir sırada tutan Sanal Gruplar veya Günlüklerdir ve kullanıcıların Kafka Sunucuları arasında kolaylıkla veri gönderip almasına olanak tanır. Kullanıcı tarafından isimlendirilirler. Bir Kafka cluster’ında binlerce topic olabilir.</p><p><strong>Kafka Broker</strong></p><p>Kafka sunucusunun kendisidir.</p><p>Broker’lar Kafka Cluster’ı oluşturan sunuculardır. Her broker birer sayıdan oluşan ID ile tanımlıdır. Kafka Cluster oluşturulurken broker sayısı üç gibi bir sayıyla başlar, gereksinim arttıkça ilave edilir. Yüzün üstünde broker koşturan sistemler de vardır.</p><p>Bağlandığımız sunucu bootstrap broker adını alır. Bootstrap broker’a bağlanınca tüm broker’ların bilgisinin tutulduğu metadata sayesinde diğer broker’ların adreslerine erişilir. Tüm kafka cluster’a bağlanmak için sadece bootstrap broker’a bağlanmak yeterlidir.</p><p>Kafka dağıtık yapıda olduğu için tek bir broker topic’in tamamını alamaz. Her broker topic’in belli kısımlarını (partition) alır. Brokerlara partition’ların dağıtımı, eşit şekilde yapılmaya çalışılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqPRJ2SensBYHO73PW8mKQ.png" /></figure><p><strong>Consumer:</strong></p><p>Consumer, belli bir topic’den mesaj okuyan Kafka bileşenidir.Consumer topiclere bağlanan(Comsumer topic’e join olur) Topic’i baştan başlayarak okumaya başlar.</p><p>Partition’lardan paralel şekilde okuma yapar. Partition bazında sırayla okur. Partition’lar arası sırayla okuma yapamaz. İki partition’dan okuma yapıyorsa birinde 5. indexde diğerinde 20. indexde olabilir.</p><p>Consumer’lar verileri consumer group’lar halinde okur. Tek de olsa her consumer’ın bir grubu vardır. Grubu biz oluşturmazsak Kafka otomatik olarak oluşturur.</p><p>Gruptaki her consumer belli partition’lardan okuma yapar. Mesela topic’imizde 3 partition varsa:</p><ul><li>3 consumer’ımız varsa her consumer birer partition’dan okuma yapar.</li><li>2 consumer’ımız varsa biri tek partition’dan, biri kalan iki partition’dan okuma yapar.</li><li>4 consumer’ımız varsa biri inaktif olur diğer üçü birer partition’dan okuma yapar. Gruptaki bir consumer’ın çökmesi gibi durumlara karşı bazen bu şekilde partition sayısından fazla consumer kullanıldığı olur.</li></ul><p>Genel olarak Kafka’nın bileşenlerinden bahsetmiş olduk. Şimdi bir process Kafka’da nasıl ilerliyor ona bakalım. Ve bu anlatımı Spring Boot projesi ile örneklendirerek bilgimizi kod’a dökelim.</p><p>Bir tane Kafka cluster bize teslim edildi ondan sonraki süreçte ilk yapmamız gereken Topic üretmek. Misal Logs adında bir tane topic yarattık. Bu topic’in görevi sistemimizde üretilecek logları toplamak olsun.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1c2f2a07efca1da3c47609b6cccc014/href">https://medium.com/media/f1c2f2a07efca1da3c47609b6cccc014/href</a></iframe><p>Bu log topic’iği producer gönderdiği sürece sistemimizin üretmiş olduğu logları toplamaya başlayacak. O zaman producer’imizi üretelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d723fed161edd38f96f50a98408fea2/href">https://medium.com/media/2d723fed161edd38f96f50a98408fea2/href</a></iframe><p>Yukarıdaki kodu inceleyelim.</p><p><strong>boostrapServers</strong> bizim kafka clusterımıza karışılk geliyor. application.properties icerisinde ;<br>spring.kafka.bootstrap-servers=localhost:9092<br>olarak tanımyalabilirsiniz.</p><p><strong>producerConfig</strong> ise producer’imizin nasıl özellikler barındıracağını belirtiyorsunuz. ProducerConfig class ile producer’imizi özelleştirebiliriz.</p><p><strong>DefaultKafkaProducerFactory</strong> ise producerConfig özellikleri ile bize singleton bir producer instance oluşturmamızı sağlar.</p><p><strong>KafkaTemplate</strong> high-level operasyonları yönetmemizi sağlıyor.</p><p>Not: Buradaki logların String olarak geleceğini kabul ettik. Fakat isterseniz object olarakda alabilirsiniz, yada kendi yarattığınız bir model de olabilir.</p><p><strong>Davranışsal olarak Producer hareketleri ;</strong></p><p>Producer kendisinde tutulan datayı topic’e iletir eğer herhangi bir data yoksa topicde sıfırıncı index’e onu depolar ve durum bilgisini geri dönderir. Eğer icerisinde bir data bulunuyorsa o zaman devam eden index de(5.index olsun) o kaynağı sıradaki index’e kaydetmeye başlayarak durum bilgisini döner. Ve tüm sürec bu sıra ile gerçekleşir.</p><p><strong>Consumer</strong></p><p>Comsumer belirtilen topic’i(Burada logs topic) baştan sona tüm indexleri okumaya başlar. eğer okumaya birşey kalmaz ise consumer kendisini beklemeye alır. Eğer topic update olursa otomatik olarak consumer ilgili topici okumaya başlıyor</p><p>Comsumer’in java tarafında uygulanmasını aşağıda görmektesiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78b9867db63adc8cc80cf189d915baa9/href">https://medium.com/media/78b9867db63adc8cc80cf189d915baa9/href</a></iframe><p><strong>Kafka Mutli Partition ile Producer &amp; Consumer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p33HggYGiunT5tKdaO6CFQ.png" /></figure><p>Mesajlar her zaman bir key-value yapısına sahiptir; bir key veya value boş olabilir. Producer verilerin nereye yazılacağını belirtmezse, Broker, iletileri bölmek ve çoğaltmak için Key’i kullanır. Key boş olduğunda, mesajlar sıralı dağıtım kullanılarak dağıtılır.</p><p><strong>Consumer’ın</strong> görevi topic’e bağlanmak. Eğer bağlanacak multiple bir partition yok ise direk gidip var olan partition ‘a join oluyor. Eğer partition’u oku denildiği zaman okumaya başlıyor. Multiple Partitionda ise hangi partitionu okuyacağınza configurasyon ayarında belirterek ilgili consumerin sadece ilgili partition’u okumasını sağlıyor ve diğer partitionları kullanmadan süreci devam ettirebiliyoruz.</p><p><strong>Apache Kafka Sub/Pub Modeli.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOkXRhNlSe2TIOWJQSTKaQ.png" /></figure><ul><li>Düzenli aralıklarla, Kafka Producer mesajı bir Topic’e gönderir.</li><li>Kafka Brokers , tüm mesajları belirli bir Topic için yapılandırılmış partitionlarda saklayarak, mesajların partitionlar arasında eşit dağılımını sağlar. Örneğin, Producer iki mesaj gönderirse ve iki partition varsa, Kafka bir mesajı ilk partitionda ve ikinci mesajı ikinci partitionda saklayacaktır.</li><li>Ayrıca, Kafka Consumer belirli bir topic’e abone olur.</li><li>consumer bir topic’e sub olduğunda, Kafka topic’in mevcut ofsetini consumer’a sunar ve ofseti Zookeeper topluluğuna kaydeder.</li><li>Ayrıca, consumer yeni mesajlar için (100 Ms gibi) düzenli aralıklarla veriyi isteyecektir.</li><li>Kafka, Producerlardan aldığı mesajları en kısa sürede consumera iletecektir.</li><li>consumer mesajı alacak ve işleyecektir.</li><li>Ardından Kafka Broker işlenen iletinin bir ack’sini alır.</li><li>Ayrıca, Kafka bir act alır almaz ofset değiştirilir ve yeni değere güncellenir. ZooKeeper ofsetleri koruduğu için, sunucu saldırıları sırasında bile tüketici sonraki mesajı doğru bir şekilde okuyabilir.</li><li>Ancak consumer talebi durdurana kadar akış tekrar eder.</li><li>Bir avantaj olarak, tüketici herhangi bir zamanda bir Topicin herhangi bir ofsetini geri sarabilir/atlayabilir ve ayrıca tüm sonraki mesajları bir arzu olarak okuyabilir.</li></ul><p><strong>Kafka’da Consumer Grouplar</strong></p><ul><li>Partitionların paralel olarak işlenmesi için kullanılır. <strong>Normal şartlarda bir Consumer bir partition okumaktan sorumludur.</strong></li><li>Consumer group ile Kafka pub/sub metodlarını aynı anda sağlabilmemize olanak sağlıyor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*czkU4HchnOMtfgFbyZU_oA.png" /></figure><p>Normalde ideal olan yöntem her bir consumer’ın bir tane partition’u okumadan sorumlu olması gerekirç. Fakar biz istersek aynı partitionu birden fazla consumerın okumasını sağlayabiliriz. Bunu ise consumer grouplar ile sağlıyoruz.</p><p>Yukarıdaki şekli incelersek consumer group 0 da yer alan comsumer 0 broker 0 daki topico partitionuna join oluyor. fakat aynı anda Topic 0 daki topico partition’a consumer group 1 deki consume 0 da join oluyor.</p><p>Buradaki önemli nokta daha önce bahsettiğimiz consumerların topiclere bağlanma görevi artık evrilerek partitionlara yöneldiğini fark edeceksiniz. Burada topic’e join olma artık consumer group’un olurken partition’a bağlanma ise consumer group da yer alan consumer X e ait.</p><p>Peki 2 partitiona 3 tane consumer bağlayabilirmiydik ? Bu sorunun cevabı hayır. Çünkü consumer groupların görevi aslında bir load balance görevi görüyor. 3 tane consumer icerisinde consumer 1 ve consumer 2 ilgili partitionlara attech olurken consumer 3 ise boşta kalacaktı.</p><h3>Topic Replication</h3><p>Dağıtık sistemlerin avantajlarından biri, sunuculardan biri offline olsa bile sistemin sürdürebilir durumda olmasıdır. Kafka’da da replica’lar sayesinde sistemin devam etmesi ve veri kaybının önüne geçilmesi sağlanır.</p><p>Replication ile topic’lerin her partition’u birden fazla sunucuda saklanır. Bu sunuculardan biri leader’dir, diğerleri ISR (in-sync replica) denilen kopyasıdır. ISR’ler veriyi senkronize eden, kopyasını tutan pasif sunuculardır, veri alışverişi leader üzerinden sağlanır. Leader ve ISR’ler zookeeper tarafından belirlenir. Replication’lar topic oluşturulurken replication-factor parametresi ile belirtilirler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg4cqyiemO0m5_RwpPyePg.png" /></figure><p>replication factor’ü 3 ve partition sayısı 4 olan Topic 1 görünmektedir. Partition 1 için 1 nolu broker leader 2 ve 3 nolu broker’lar ISR pozisyonundadır. Partition 2 içinse 3 nolu broker leader 1 ve 4 nolu broker’lar ISR’dir. Bu şekilde her partition için lider ve replica’lar tüm broker’larda dağıtık olarak tutulurlar.</p><p>Her partition’un leader’i farklı broker’larda olabilir. Bir partition için aynı anda sadece bir tane leader vardır. Örneğin partition 1 için leader olan broker 1 offline olursa veya çökerse broker 2 veya broker 3 lider pozisyona geçecektir. Broker 1 ayağa kalkınca tekrar leader olacaktır.</p><p>Sources :</p><p><a href="https://www.confluent.io/what-is-apache-kafka/">https://www.confluent.io/what-is-apache-kafka/</a><br><a href="https://aws.amazon.com/msk/what-is-kafka/">https://aws.amazon.com/msk/what-is-kafka/</a></p><p><a href="https://kafka.apache.org/">https://kafka.apache.org/</a><br><a href="https://www.veribilimiokulu.com/apache-kafka-temel-kavramlar/">https://www.veribilimiokulu.com/apache-kafka-temel-kavramlar/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e1e5dc211e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga design pattern and transaction in Microservices architectures]]></title>
            <link>https://cedellalahmet.medium.com/saga-design-pattern-and-transaction-in-microservices-architectures-3d4c4fe36337?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4c4fe36337</guid>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 14:47:15 GMT</pubDate>
            <atom:updated>2022-03-03T14:47:15.859Z</atom:updated>
            <content:encoded><![CDATA[<p>As it is generally known, design patterns are the method that will solve a design problem in the simplest and most effective way in project development. So let’s say you’re going to move from besiktas to uskudar. your design template should tell you to get on the ferry. Otherwise, it is possible to go from Beşiktaş to Uskudar via Australia.</p><p>For more detailed information, <a href="https://refactoring.guru/">see here.</a></p><p><strong><em>Ps</em></strong>: Esign patterns either show themselves by sitting on the template at the very beginning or they are started to be used later due to necessity. The places where the design pattern will be used start from the place where the change in the code is known or likely to change. Many examples of singletons have been given. You can explode a multithreaded application using a singleton. For this and other reasons, a singleton antipattern debate is made. If we say that the design pattern is a solution design of a problem, we define it incompletely. Using that solution that makes a pattern into a pattern 3 or 4 times in real world applications is a kind of common knowledge.</p><p>I’ll continue without messing up :)</p><p>As it is known, it is accepted that every service should ideally have its own database in microservice architectures. Such services are called distributed transactions. Since each service has its own database, there must be holistic data consistency between each service. so naturally, if each service has its own database, then it is inevitable to have a holistic hierarchy among these services. Let me explain with an example.</p><p>Let’s say you are developing in the order department at Amazon. Let’s say that we do the order taking process in the ‘Order’ services, the stock transactions after the order in ‘Stock’ and finally the payment transactions in the ‘Payment’ services of this software. Of course, let’s consider that all these services have their own databases, as we mentioned in the paragraphs above, and let’s assume that the operations proceed as follows from a scenario perspective:</p><pre>When the user places an order for any product, the &#39;Order&#39; service will perform this operation and add it to its own database. The &#39;Payment&#39; service will provide the payment and if the payment is successful, it will reduce the stock amount corresponding to the relevant product in the &#39;Stock&#39; service.</pre><p>Now, in this process, if the ‘Payment’ service successfully completes the payment for that order after the ‘Order’ service creates the incoming order, the stock number of the relevant product in the order in the ‘Stock’ service must be reduced. Otherwise, an inconsistency will occur. Think about it, after the order is placed and the payment is made, the stock still remains the same. Think of the damage this has done to the data statistics in the software and to the business using that software!</p><p><strong>What are Transaction, Distributed Transaction and Compensable Transactions?</strong></p><p><strong>Transaction :</strong></p><p>You could say everything we do in the database. This is how the incoming scope passes. Basically, if there is a problem in the process of an operation we have done on the database, it is useful to cancel the transaction and roll it back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*76N2VelAHDFVggGyLOT5ng.png" /><figcaption>Transaction status</figcaption></figure><p><strong><em>Distributed Transaction:</em></strong></p><p>This term, which refers to the situation where more than one different database works as a whole, is used for distributed database systems. Generally, in approaches such as microservices, each service moving its own database is considered a distributed transaction. <a href="https://hazelcast.com/glossary/distributed-transaction/">Refer</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*r8CHUvSizfTviSxv.png" /></figure><p><strong><em>Compensable Transaction</em></strong></p><p>Compensable Transaction, on the other hand, is to take the reverse of what a transaction has done. In other words, the retrospectiveness of a committed transaction is only possible with compensation after this time. This backward compensation process is called compensable transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*p8ECA0yo72AuqGC4MToEWw.png" /></figure><p>I believe it will be more enlightening if we examine the figure above. Let me explain with a simple example; The customer came with an order. then we directed it to calculateservice to calculate all the price of this order. In the next step, it is directed to the payment service and the payment step is provided. To put it more simply, the customer has listed the products with the price of x units of money, and the fee has been created. In order to obtain this from the customer, the relevant bank is asked to deduct x units of money. In this case, x units of money are deducted from the customer’s bank account. If any problem occurs, x units of money deducted from the relevant bank will be returned to the customer’s bank account. Here, reverting the work done in all services in case of any negative situation is a compensable transaction.</p><p>The core characteristic of the microservices architecture is the loose coupling of services. To achieve that, each service must have its own private data store. So, building the database architecture for microservices almost always requires following the database-per-service pattern. At least up till the point where the application hasn’t got too complex yet, with numerous services involved.</p><p>Let’s take a look at an online store application. Order Service and Customer Service each store data in their own databases. Changes to one database don’t impact other microservices. <br>Actually this method has a name : The Database-per-Service pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*CFkviFzWEdgQE0Dz9ZICYg.png" /></figure><p>The most important of these, we can say, is a very difficult and laborious function to query data by joining (join) data between databases and to produce holistic statistical results.<br>The service’s database can’t be accessed directly by other microservices. Each service’s persistent data can only be accessed via API.</p><h3>ACID properties of transactions</h3><pre>As a result of any data interference with a software on distributed databases, we evaluate how this process will be implemented in line with certain principles.</pre><p>In the context of transaction processing, the acronym ACID refers to the four key properties of a transaction: atomicity, consistency, isolation, and durability. <a href="https://www.ibm.com/docs/en/cics-ts/5.4?topic=processing-acid-properties-transactions">refer</a>!</p><p><strong>Atomicity</strong> <br>All changes to data are performed as if they are a single operation. That is, all the changes are performed, or none of them are.For example, in an application that transfers funds from one account to another, the atomicity property ensures that, if a debit is made successfully from one account, the corresponding credit is made to the other account.</p><p><strong>Consistency</strong><br>Data is in a consistent state when a transaction starts and when it ends.For example, in an application that transfers funds from one account to another, the consistency property ensures that the total value of funds in both the accounts is the same at the start and end of each transaction.</p><p>In this principle, logic refers to the success of all transactions throughout a transaction process. It is the state of undoing the entire transaction in case any operation fails. In short, all or nothing.</p><p>Let’s consider two services, if the X record in the first of these services corresponds to the Y record in the other service, there is no problem. But if there is no record in the first service, but there is a Y record in the second service, the alarm should sound. Because data must be consistent in distributed databases. We may encounter unexpected situations in later processes.</p><p><strong>Isolation</strong></p><p>The intermediate state of a transaction is invisible to other transactions. As a result, transactions that run concurrently appear to be serialized.For example, in an application that transfers funds from one account to another, the isolation property ensures that another transaction sees the transferred funds in one account or the other, but not in both, nor in neither.</p><p>The isolation of the services with each other is important. What he means is that in the case of sequential transactions, if each transaction is dependent on the result of the previous transaction, we should wait for it, if not, we should ring alarm bells and shut ourselves down. Let me explain with an example: Let’s consider an e-commerce application, the customer added the products to his cart. Normally, the simple thing to do is to go to the payment step, but there is such a situation that we took the order directly and started to deliver the product without going to the payment step. In this case, a question like who wrote this code comes up.</p><p><strong>Durability</strong> <br>After a transaction successfully completes, changes to data persist and are not undone, even in the event of a system failure.For example, in an application that transfers funds from one account to another, the durability property ensures that the changes made to each account will not be reversed. store data in the safest place. whether on cd, disk or cloud service :)</p><p><strong>What is the SAGA ?</strong></p><p>A saga is a sequence of local transactions where each transaction updates data within a single service. The first transaction is initiated by an external request corresponding to the system operation, and then each subsequent step is triggered by the completion of the previous one.</p><p>Types of saga pattern The two ways to perform sagas:</p><p><strong>Choreographic sagas</strong>:<br>In this type, the domain events act as triggers. The first transaction is initiated by an external request or user’s input,then each localtransaction publishes domain events into event bus that will trigger local transactions in other services.</p><p><strong>Benefits</strong> :</p><p>This is a natural and easy way of implementing saga pattern. </p><p>This is easy to understand and will not require too much effort to develop. </p><p>All the services are loosely coupled so it does not violate the principle of microservices.</p><p><strong>Drawbacks</strong> :</p><p>As the number of services increases or local transactions increase, this method become more complex and cumbersome because it can have cyclic dependency between the stages of saga. </p><p>Testing would become complex as all the participants should be running.</p><p><strong>Orchestration sagas:</strong></p><p>An orchestrator or centralized controller tells the participants or services what local transactions to execute.</p><p><strong>Benefits</strong>: </p><p>We can avoid cyclic dependencies between participants. </p><p>Complexity can be reduced as participants only have to execute and reply for the commands.</p><p><strong>Drawbacks</strong>: </p><p>Too much load on the orchestrator or centralized controller because we will be concentrating on the orchestrator logic.</p><p>Increase in the infrastructure complexity because we need to add extra service.</p><p><strong>SAGA — EVENTS/CHOREOGRAPHY</strong></p><p>In this approach every change to the state of an application is captured as an event. This event is stored in the database/event store (for tracking purposes) and is also published in the event-bus for other parties to consume.</p><p>In other words, when the transaction, which started in the first service, is finished, it will send an event via the message broker (kafka, RabbitMQ etc.). When the transaction is completed in the transmitted service, it will send another event via the message broker in the same way. All of these processes will continue until the process requested by the client is completed.</p><pre>In Choreography, each service queue listens. If there is a message that comes according to the event message type it listens, it performs the necessary operations and as a result, it adds the successful or unsuccessful information to the queue as an event. Then, other services will either continue their functions according to this event, or all transactions will be restored and data consistency will be ensured.</pre><p>Example below is from <a href="https://www.vinsguru.com/choreography-saga-pattern-with-spring-boot/">vinsguru</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhaVQgNHSX04jzyF2y5csA.png" /></figure><p>The business workflow is implemented as shown here.</p><ul><li>order-services receives a POST request for a new order</li><li>It places an order request in the DB in the ORDER_CREATED state and raises an event</li><li>payment-service listens to the event, confirms about the credit reservation</li><li>inventory-service also listens to the order-event and conforms the inventory reservation</li><li>order-service fulfills order or rejects the order based on the credit &amp; inventory reservation status.</li></ul><pre>Abstract : In this implementation, it is essential to communicate with each other through events without a central control and communication point between microservices. In other words, he argues that communication between services should be designed asynchronously.</pre><p>Code <a href="https://github.com/vinsguru/vinsguru-blog-code-samples/tree/master/architectural-pattern/saga-choreography">Example</a> github link .</p><p>Let’s see how it would look like in our e-commerce example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*-irO5evlmB_qt4UHLsrzdQ.png" /></figure><ol><li><em>Order Service</em> saves a new order, set the state as <em>pending</em> and publish an event called <strong><em>ORDER_CREATED_EVENT</em></strong>.</li><li>The <em>Payment Service</em> listens to <strong><em>ORDER_CREATED_EVENT</em></strong>, charge the client and publish the event <strong><em>BILLED_ORDER_EVENT</em></strong>.</li><li>The <em>Stock Service</em> listens to <strong><em>BILLED_ORDER_EVENT</em></strong>, update the stock, prepare the products bought in the order and publish <strong><em>ORDER_PREPARED_EVENT</em></strong>.</li><li><em>Delivery Service</em> listens to <strong><em>ORDER_PREPARED_EVENT</em></strong> and then pick up and deliver the product. At the end, it publishes an <strong><em>ORDER_DELIVERED_EVENT</em></strong></li><li>Finally, <em>Order Service</em> listens to <strong><em>ORDER_DELIVERED_EVENT</em></strong> and set the state of the order as concluded.</li></ol><p>In the case above, if the state of the order needs to be tracked, Order Service could simply listen to all events and update its state.</p><h4>Rollbacks in distributed transactions</h4><p>Rolling back a distributed transaction does not come for free. Normally you have to implement another compensating transaction for what has been done before.</p><p>Suppose that Stock Service has failed during a transaction. Let’s see what the rollback would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71sRkH63mrck36WBGP7MMg.png" /></figure><ol><li><em>Stock Service</em> produces <strong><em>PRODUCT_OUT_OF_STOCK_EVENT</em></strong>;</li><li>Both <em>Order Service</em> and <em>Payment Servic</em>e listen to the previous message:</li></ol><p>2.a P<em>ayment Service</em> refund the client</p><p><em>2.b Order Service</em> set the order state as failed</p><p>Note that it is crucial to define a common shared ID for each transaction, so whenever you throw an event, all listeners can know right away which transaction it refers to.</p><h4>Benefits and drawbacks of using Saga’s Event/Choreography design</h4><p>Events/Choreography is a natural way to implement a Saga orchestration pattern. It is simple, easy to understand, does not require much effort to build, and all participants are loosely coupled as they don’t have direct knowledge of each other. If your transaction involves 2 to 4 steps, it might be a very good fit.</p><p>However, this approach can rapidly become confusing if you keep adding extra steps in your transaction as it is difficult to track which services listen to which events. Moreover, it also might add a cyclic dependency between services as they have to subscribe to one another’s events.</p><p>Finally, testing would be tricky to implement using this design, in order to simulate the transaction pattern you should have all services running.</p><p><strong>SAGA — COMMAND/ORCHESTRATİON</strong></p><p>In this approach, the inter-service distributed transaction is coordinated with a central controller. This controller is called the Saga State Machine, or another name, the Saga Orchestrator. Saga Orchestrator manages all operations between services and tells which operation to take based on events.</p><pre>As its other name, Saga State Machine, can be understood, Saga Orchestrator keeps the application state of each request from each user, interprets it and applies compensatory operations when necessary.</pre><p>Let’s see how it looks using our e-commerce example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YRo6BxNdbQbINu00GHmLw.png" /></figure><ol><li><em>Order Service</em> saves a pending order and asks Order Saga Orchestrator (OSO) to start a <em>create order transaction</em>.</li><li><em>OSO</em> sends an <strong><em>Execute Payment</em></strong> command to <em>Payment Service</em>, and it replies with a <strong><em>Payment Executed</em></strong> message</li><li><em>OSO</em> sends a <strong><em>Prepare Order</em></strong> command to Stock Service, and it replies with an <strong><em>Order Prepared</em></strong> message</li><li><em>OSO</em> sends a <strong><em>Deliver Order</em></strong> command to Delivery Service, and it replies with an <strong><em>Order Delivered</em></strong> message</li></ol><p>In the case above, Order Saga Orchestrator knows what is the flow needed to execute a “create order” transaction. If anything fails, it is also responsible for coordinating the rollback by sending commands to each participant to undo the previous operation.</p><p>A standard way to model a saga orchestrator is a State Machine where each transformation corresponds to a command or message. State machines are an excellent pattern to structure a well-defined behavior as they are easy to implement and particularly great for testing.</p><h3>Rolling Back in Saga’s Command/Orchestration</h3><p>Rollbacks are a lot easier when you have an orchestrator to coordinate everything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf-FOXjolNW0D4GGAv5sOA.png" /></figure><ol><li><em>Stock Service</em> replies to OSO with an <strong><em>Out-Of-Stock</em></strong> message;</li><li>OSO recognizes that the transaction has failed and starts the rollback<br>2.1 In this case, only a single operation was executed successfully before the failure, so <em>OSO</em> sends a <strong><em>Refund Client</em></strong> command to <em>Payment Service</em> and set the order state as failed</li></ol><pre>Here, in case of an error or a failure of the transaction, the orchestrator receives the information that there is a failure in the transaction process and starts the rollback transactions(Compensable Transaction)</pre><pre>Keeping state information on Saga for each process will make it easier to see which step you mismanaged the process.</pre><h3>Benefits and Drawbacks of Using Saga’s Command/Orchestration Design</h3><p>Orchestration-based sagas have a variety of benefits:</p><ul><li>Avoid cyclic dependencies between services, as the saga orchestrator invokes the saga participants but the participants do not invoke the orchestrator</li><li>Centralize the orchestration of the distributed transaction</li><li>Reduce participants’ complexity as they only need to execute/reply commands.</li><li>Easier to be implemented and tested</li><li>The transaction complexity remains linear when new steps are added</li><li>Rollbacks are easier to manage</li><li>If you have a second transaction willing to change the same target object, you can easily put it on hold on the orchestrator until the first transaction ends.</li></ul><p>However, this approach still has some drawbacks, one of them is the risk of concentrating too much logic in the orchestrator and ending up with an architecture where the smart orchestrator tells dumb services what to do.</p><p>Another downside of Saga’s Orchestration-based is that it slightly increases your infrastructure complexity as you will need to manage an extra service.</p><pre>The links to the sources I used during the writing period are below.</pre><pre>Sources:</pre><pre><a href="https://blog.couchbase.com/saga-pattern-implement-business-transactions-using-microservices-part/">https://blog.couchbase.com/saga-pattern-implement-business-transactions-using-microservices-part/</a></pre><pre><a href="https://www.irjet.net/archives/V7/i5/IRJET-V7I5124.pdf">https://www.irjet.net/archives/V7/i5/IRJET-V7I5124.pdf</a></pre><pre><a href="https://microservices.io/patterns/data/saga.html">https://microservices.io/patterns/data/saga.html</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4c4fe36337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Golang.]]></title>
            <link>https://cedellalahmet.medium.com/generic-programming-is-a-style-of-computer-programming-in-which-algorithms-are-written-in-terms-of-4c102864806b?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c102864806b</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 12:10:07 GMT</pubDate>
            <atom:updated>2022-02-28T12:14:24.816Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Generics in Golang.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*Zt33bLvkkWrHzzG9z7OpaQ.jpeg" /></figure><p>Why do programming languages ​​need Generics?</p><p><strong>Generic programming</strong> is a style of <a href="https://en.wikipedia.org/wiki/Computer_programming">computer programming</a> in which <a href="https://en.wikipedia.org/wiki/Algorithm">algorithms</a> are written in terms of <a href="https://en.wikipedia.org/wiki/Data_type">types</a> <em>to be specified later</em> that are then <em>instantiated</em> when needed for specific types provided as <a href="https://en.wikipedia.org/wiki/Parameter_(computer_programming)">parameters</a>. (Source: <a href="https://en.wikipedia.org/wiki/Generic_programming">https://en.wikipedia.org/wiki/Generic_programming</a>)</p><p>That is, in strongly typed programming languages, because the type must be given first. It is difficult to write abstract writing when writing functions. Let the models be embedded after the fact. Take a simple example according to the article “<a href="https://go.dev/blog/why-generics">Why Generics</a>” once gave this great example. Suppose you need to sort all the items in a slice from smallest to largest.</p><p>With int you can write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25ed7179c6337037c5de22655c70b9e2/href">https://medium.com/media/25ed7179c6337037c5de22655c70b9e2/href</a></iframe><p>And if it’s a string, it could be something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/844cbd0073b0447ad69a5690f2725e87/href">https://medium.com/media/844cbd0073b0447ad69a5690f2725e87/href</a></iframe><p>According to the above method, you will see that there is really no difference between the two functions. However, due to the different data formats, the two functions have to be written separately. Maintenance this way is often unintuitive. Once it is found that it can be optimized or there is a problem in the future, all code used in the type needs to be retained at once, which is quite unintuitive.</p><p>No alternative to Golang before Type Parameters?</p><pre>Let&#39;s not talk about Generics, actually Golang can do related development via Interfaces. Here is the relevant implementation method. Let&#39;s first explain what interfaces are:</pre><p>refer: <a href="https://gobyexample.com/interfaces">Go By Example</a>: <a href="https://gobyexample.com/interfaces">interfaces</a></p><p>Based on this example, you can easily understand the main usage of interfaces. What is the known application method? is the sort.Sort()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a9f225396e3262e96f099a0f3ca9a80/href">https://medium.com/media/7a9f225396e3262e96f099a0f3ca9a80/href</a></iframe><p>Via the sort.Sort() function, you can set the sorting method of int or string, and you can even define your own Len(), Swap(), and Less() for the custom structure and then apply the sort.Sort(). . Of course, methods such as Go rendering, mirroring can also be used. I won’t go into details here and you can refer and read more. extended reading.</p><ul><li><a href="https://appliedgo.net/generics/">Who needs generics? Use … instead!</a></li></ul><h3>Golang Generic Proposal</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWzgLqE-3IhY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWzgLqE-3IhY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWzgLqE-3IhY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c7d9cbab9c58f6e63953f770d1b0838/href">https://medium.com/media/2c7d9cbab9c58f6e63953f770d1b0838/href</a></iframe><pre>What happened to contracts?<br>An earlier draft design of generics implemented constraints using a new language construct called contracts. Type lists appeared only in contracts, rather than on interface types. However, many people had a hard time understanding the difference between contracts and interface types. It also turned out that contracts could be represented as a set of corresponding interfaces; there was no loss in expressive power without contracts. We decided to simplify the approach to use only interface types.</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a1ccbc29688980eb89cef7829d413a/href">https://medium.com/media/69a1ccbc29688980eb89cef7829d413a/href</a></iframe><p>Using anyTip Parametresi is actually quite convenient, but often depends on the data you may be dealing with when it is not suitable for all types. In fact, some data restrictions need to be added. Give an example to illustrate: Example: Take the larger of the two parameters</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4816fe9aad1c1ce6da67f27d6e012198/href">https://medium.com/media/4816fe9aad1c1ce6da67f27d6e012198/href</a></iframe><p>It’s a fairly simple way of comparing, but you can see how this could be written through Tip Parametreleri. It will be found that the input parameters will not support string , so the following related modifications are required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f96dc847f6e391297946c314ebffdb9/href">https://medium.com/media/2f96dc847f6e391297946c314ebffdb9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c102864806b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why software engineer ?]]></title>
            <link>https://cedellalahmet.medium.com/the-philosophy-of-software-development-860e77653859?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/860e77653859</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 09:39:28 GMT</pubDate>
            <atom:updated>2021-10-11T05:27:58.362Z</atom:updated>
            <content:encoded><![CDATA[<p>Software development is considered a field ruled by logic. Every decision we make is guided by rules that we can follow and understand. Every problem has an engineering solution. Every opinion can be either true or false.</p><p>If you’ve spent some time in the software industry you know that this is not true. We make decisions in an ever-changing environment and solving them requires more than pure technical knowledge. The same opinion can be true or false depending on the situation. The most common answer to a question is — “It depends”.</p><p>We dive into endless debates on the maturity of technologies, the benefits of different code styles, the best amount of indentation — the list goes on. We still question whether established practices still provide the best value in the current state of software engineering.</p><p>The question of “Why”, which is the philosopher’s stone of philosophy, is the first holy word that always questions and those who want to explain around logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*ob7qo8qlHCm8wPKD.png" /></figure><p>I truly cherish working in a field in which everything is questioned because that’s the only way we can uncover the truth. But what does truth actually mean? Can something be true at all? Maybe the answers I get make sense for the problem we are solving but are completely faulted in a different environment.</p><p>By continuously asking questions and debating different ideas we actually go into philosophical debates. We aim to uncover the final reason of things — the root cause. Of course, sometimes we just try to persuade the other side to believe the same as us but those conversations are not truly debates.</p><p>Sometimes we philosophise about general engineering topics like tabs or spaces. For many of those big picture questions we need to accept an answer for ourselves and form our own reality.</p><p>However there are questions which have less of an impact and therefore can be answered more specifically. Question whose truth only affects our company or our team. One of the commonly asked question is “Why is this done this way?”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*V85Nl9P4UdDyOjqO.png" /></figure><p>We aim to challenge ideas and seek wisdom rather than solve engineering problems. Once the question becomes technical then solving it is easier. Reaching that point is hard.</p><p>Instead of trying to find the answers ourselves should we just rely on already established opinions? When is a problem too specific for its solution to be decided by common knowledge?</p><p>When asking philosophical questions we aim to challenge the beliefs, thoughts and feelings for a specific topic. So when someone asks about the philosophy of functional programming this is the sort of things they have in mind.</p><p>Software engineering is a relatively new field and many truths about it are yet to be formed as a system. But we can’t spend our time arguing about what is right or wrong. In the end of the day we’ll have to make a few hard decisions and do our best to build a good software product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*CGoSnH9hF__Z2kVo.png" /></figure><p>But how much context, opinions and thoughts do we want to exchange before we do that? This is another difficult question on its own.</p><p>This article asks more questions than it gives answers to. I suppose this is the way with every deep discussion. You recursively ask the question “why” until you hit the bottom and the function returns</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=860e77653859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Serverless?]]></title>
            <link>https://cedellalahmet.medium.com/what-is-serverless-87467ba5f860?source=rss-8ef3c3229866------2</link>
            <guid isPermaLink="false">https://medium.com/p/87467ba5f860</guid>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Ahmet DELLAL]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 13:33:52 GMT</pubDate>
            <atom:updated>2021-07-20T13:33:52.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Imagine a vacation, its nights pitch dark, quiet, and gloomy. Hot and angry during the day. Again on such a day, with the cries of help from a friend, I took my armor and sword from the place that I used as a warehouse when I was a kid and got ready to come to his aid. The distance between us was so ancient and distant that it would be impossible for me to catch up with the known vehicles. Instead, I accessed my friend by connecting my computer to the internet, which the magic school had recently developed by analyzing the technology of ancient times, combining the technology of magic and today’s world. After all, magic was a field that science could not explain or knowledge was insufficient. That’s why sorcerers were not at all unfamiliar with this technology.</h3><h3>Anyway, without confusing you with the knowledge of the ancients, let’s get back to the topic with the help of my more friends. He asked for my help from a couple of points where he was stuck with the serverless they used in the project he was working on. It took a while, but we solved it, after all, no matter how many people go around the serverless architecture, it seems like it will hand over its throne with cloud 2.0. After all, there is an order based on making each newcomer forget the old one.</h3><p>ps: In the picture below, you see the messenger of mother nature for blessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StHmeUPhSAbkzNxVxEolvw.jpeg" /><figcaption>Adıyaman Tut</figcaption></figure><p>So what comes to mind when we say serverless?</p><ul><li>Anything that looks like “Function as a Service” like AWS Lambda, Google Cloud Functions, and Azure Functions</li><li>Anything that can <em>run</em> a Function as a Service system, like OpenFaaS and similar</li><li>Ok… lots of people think it’s a synonym for Function as a Service (spoiler: it’s not)</li><li>Any solution that runs “on-demand compute” such as Google App Engine (spoiler: it’s not)</li><li>Anything that runs a container on demand like Google Cloud Run or Fargate (I don’t know much about Google, isn’t it nice to see my shortcomings by typing :D)</li><li>Basically “on-demand compute” of some description, some of which “scales to zero”</li></ul><p>And you’ll often find fans of technologies such as kNative and Kubernetes talking about how their technologies are “serverless” or “enable serverless” architectures.</p><p><em>PSA: These technologies have their place and the people who work on them are probably really nice people (I haven’t met them all, so I just don’t know). If they fill a business need for you, then fantastic, please use them. I am simply questioning whether they should be called “serverless” not whether they have intrinsic value or not.</em></p><h3>Serverless is an approach, not a technology</h3><p>Now, where did I come to this conclusion, who am I etc. But the people at the heart of the matter are saying this now. we, as individuals who learn and produce ideas from what they learn, approve what is said after the filter of reason and logic and continue on our way.</p><p>Of course, my serverless knowledge is fine, but for a person who understands and solves logic with today’s technology opportunities, it takes only 3 or 5 days to bring a new technology to the application level.</p><p>I asked my friend why you made this project serverless. hand answer(:D El cevap burası cokomelli)</p><p>I wanted to <em>limit my exposure to managing servers</em> as much as possible.</p><p>Notice that I’m not worried about managing servers. It’s my exposure to the risk that matters here.</p><p>I literally didn’t want to have to think about ssh-ing into any instances, and upgrading them regularly, monitoring them for hack attempts, maintaining any libraries on a long running system etc. <strong>unless I had no other choice</strong> due to workload constraints.</p><p>Managing servers becomes onerous <em>over time</em>, and in a startup, saving yourself time over your runway is pretty much the best thing you can do.</p><p>My choice was not to “avoid having to <em>think</em> about servers” but simply a pragmatic attempt to avoid as much of the long term work of maintaining them as I could.</p><p>It’s like saying “I can make most of this runway pretty smooth all the way along instead of really smooth to halfway, and hope that by the time we get there we’ll have the resources to make the rest really smooth too”.</p><p>Startups are hard. They require focus and things can change in an instant. You get a call and someone says “we’re now doing this — change everything” and you have to move quickly.</p><p>So what if there was a way you could do it differently? Build systems in a way that allows you to do two things:</p><ol><li>easily add to your systems and have low ongoing maintenance requirements?</li><li>easily change your systems over time without having to do a big bang rewrite/refactor?</li></ol><p>I didn’t pick Lambda and subsequently API Gateway, DynamoDB, S3, because they were cool or new, or even because Lambda scaled to zero, although the scaling to zero was an advantage.</p><p>I picked these technologies, what I call “serverless” because they provided me with a pragmatic way to achieve (what are ultimately) the business goals I had set for myself.</p><h3>Serverless is and always has been about understanding your business</h3><p>One of the key frustrations I have when talking to developers about this (and several of the product owners and advocates at big cloud vendors are at fault for this as well) is that they think they’re talking about the business, when they are really talking about technology.</p><p><strong>Because running servers or instances may be the most efficient way of achieving the business value you are trying to achieve.</strong></p><p>Which is why a “serverless architecture” based upon the criteria that many put onto it — FaaS or “on demand” — is incorrect.</p><p>Now, some may point out my definition of serverless here:</p><p><em>“A serverless application is one that provides maximum business value over its application lifecycle and one that costs you nothing to run when nobody is using it, excluding data storage costs.”</em></p><p>And you should, rightly, point out that this says it should cost you nothing if nobody is using it.</p><p>How does that square with running servers?</p><p>Well, it’s relatively simple: If nobody is using it, why are you running servers?</p><p>Servers are great for long running tasks, and for tasks where you have a relatively constant and known load. There are very few of those in the tech world that are not known in advance. Spinning up servers and containers when you have a known long running spike in load is not a bad idea either.</p><p>The key point of the definition is <em>“maximum business value”</em>.</p><p>Simply running servers because that is what you know is lazy and is not necessarily good value for the business.</p><p>Running servers because it is the right thing for business value? Go for it, but you have to make the case before you can do it, and that isn’t always easy.</p><p>The reason that FaaS is so closely intertwined with serverless is simple:</p><p><em>FaaS is the simplest and most obvious </em><strong><em>enabling technology</em></strong><em> for applications using a serverless approach</em></p><p>Well, after all that has been written, in summary:</p><p>A “systemic” thing that is actually quite “young”*, although it makes sense. huh, cloud computing is entering, you shouldn’t worry.</p><p>completely suitable for a system starting from 0; but it is a target that is not very useful in existing companies with established systems.</p><p>There are several reasons for this; But let’s talk about the reasons, first, if we look at the working principle of the serverless system:</p><p>1) While there is no technical limitation in microservices; In this system, the code written has to be written for only one thing. There is compulsion in this.</p><p>2) The written code is written independently of application lifecycle. that is, what we call infrastructure does not contain anything about the infrastructure of the software.</p><p>3) The pricing is based on time and memory usage. You know, there was the issue of comptuational complexity at the university, there was runtime complexity that we calculated both as computational and memory, here it works very well.</p><p>In summary, because of these 3 main principles, serverless asks you to write something that works fast, has a single task (after all, a main method of the code we write will work i/o); but it is not suitable to be used in any way in matters such as multi-thread, stateful (there is no shared memory after all), fault-tolerant, application configuration, special monitoring systems, interceptors, db pool, circuting.</p><p>If we get into the fault-tolerant thing, it will sit down. The code you write should be simple, if an error has occurred, it is more logical to fail this execution directly instead of fixing this error (for example, by handling the exception). because this serverless execution that is the perpetrator must be tried again by whatever is calling this execution.</p><p>On top of all this, since the serverless system takes more control from you, it may cause you to stay in the middle when you say stop tomorrow to google from amazon. I think that’s partly why it’s so supported by aws.</p><p>by the way, I want to touch on the time issue; For example, aws is charged as 100ms and its multiples; The default timeout is 60 seconds. As a maximum, this time can be up to 5 minutes. so definitely; It is not suitable to write something like back-off etc.</p><p>I listened to Paul’s speech (the guy is a type who travels like a serverless lawyer) he was beating the serverless defenders for the last time. Anyway, may the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87467ba5f860" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>