<?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 Alper Baysal on Medium]]></title>
        <description><![CDATA[Stories by Alper Baysal on Medium]]></description>
        <link>https://medium.com/@alper.baysal.?source=rss-b62dd39df4fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2AKrCmgpE359IcPrjFgwrQ.jpeg</url>
            <title>Stories by Alper Baysal on Medium</title>
            <link>https://medium.com/@alper.baysal.?source=rss-b62dd39df4fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:16:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alper.baysal./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[Kafka Producer Configs]]></title>
            <link>https://medium.com/@alper.baysal./kafka-producer-configs-342806ceb647?source=rss-b62dd39df4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/342806ceb647</guid>
            <category><![CDATA[partition]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[producer]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[kafka-producer]]></category>
            <dc:creator><![CDATA[Alper Baysal]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 19:42:26 GMT</pubDate>
            <atom:updated>2023-07-11T19:42:26.577Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is a Producer?</strong></h3><p>A Kafka producer is a component or client application that publishes or sends messages to a Kafka cluster. It is responsible for producing data records or messages to Kafka topics, which are then made available to Kafka consumers.</p><p>In Kafka, a producer is designed to be a high-throughput and fault-tolerant component that enables reliable and scalable data ingestion. It allows applications to send large volumes of data in real-time or near real-time to Kafka, which acts as a distributed and fault-tolerant message broker.</p><p>When a producer sends a message to Kafka, it publishes the message to a specific topic. The topic is a logical category or stream name to which the message belongs. Producers can publish messages to one or more topics, and each topic can have multiple partitions that allow for parallel processing and scalability.</p><h3><strong>Key Features and Functionalities of Kafka Producers</strong></h3><p><strong>Partitioning: </strong>Producers can choose to specify a key for each message, and Kafka uses this key to determine the partition to which the message is written. This allows for ordering and guarantees that messages with the same key are written to the same partition, ensuring message ordering within a partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XTrw4pRwg8zyAKqZr5dmQ.png" /></figure><p><strong>Partitions Provides Scalability</strong></p><p>If we are to put all partitions of a topic in a single broker, the scalability of that topic will be constrained by the broker’s IO throughput. By spreading partitions across multiple brokers, a single topic can be scaled horizontally to provide performance far beyond a single broker’s ability.</p><p>A single topic can be consumed by multiple consumers in parallel. Serving all partitions from a single broker limits the number of consumers it can support. Partitions on multiple brokers enable more consumers.</p><p>Multiple instances of the same consumer can connect to partitions on different brokers, allowing very high message processing throughput. Each consumer instance will be served by one partition, ensuring that each record has a clear processing owner.</p><p><strong>Partitions Provides Redundancy</strong></p><p>Kafka keeps more than one copy of the same partition across multiple brokers. This redundant copy is called a replica. If a broker fails, Kafka can still serve consumers with the replicas of partitions that failed broker owned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8393biHS0ZlDs42eABGJ8g.png" /></figure><p><strong>Async and Sync Sending:</strong> Producers can send messages either asynchronously or synchronously. Asynchronous sending allows the producer to continue processing without waiting for a response from the broker, providing high throughput. Synchronous sending waits for acknowledgment from the broker before continuing, ensuring reliable delivery but potentially impacting performance.</p><p><strong>Message Compression:</strong> Producers can enable compression for messages to reduce network bandwidth and storage costs. Kafka supports different compression codecs such as gzip, snappy, and lz4.</p><p><strong>Retries and Error Handling:</strong> Producers handle failures and errors by implementing configurable retries and error handling mechanisms. When a message fails to be delivered, producers can retry sending the message based on specified configuration settings.</p><ul><li>Retry Policy</li><li>Exponential Backoff</li><li>Dead-Letter Queue</li></ul><p><strong>Message Key and Value Serialization:</strong> Producers serialize the key and value of a message before sending them to Kafka. Serialization allows messages to be converted into byte arrays that can be efficiently transmitted and stored.</p><h3><strong>Acks (Acknowledgments)</strong></h3><p>An ack is an acknowledgment that the producer gets from a Kafka broker to ensure that the message has been successfully committed to that broker. The config <em>ACKS</em> is the number of acknowledgments the producer needs to receive before considering a successful commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxPSzpb06sx7cHGbQltgHg.png" /></figure><p>The default value is 1, which means as long as the producer receives an ack from the leader broker of that topic, it would take it as a successful commit and continue with the next message. It’s not recommended to set acks = 0, because then you don’t get any guarantee on the commit. acks = all would make sure that the producer gets acks from all the in-sync replicas of this topic. It gives the strongest message durability, but it also takes long time which results in higher latency. So, you need to decide what is more important for you.</p><h3><strong>In-Sync Replicas</strong></h3><p>When you create a topic, you must define how many replicas you want. A replica is nothing more than a copy of the message in one of the brokers, so the maximum number of replicas is the number of brokers.</p><p>Among these replicas, there is a <em>leader</em> and the rest are <em>followers</em>. The leader handles all the read and write requests while the followers passively replicate the leader.</p><p>An in-sync replica is a replica that fully catches up with the leader in the last 10 seconds. The time period can be configured via replica.lag.time.max.ms. If a broker goes down or has network issues, then it couldn’t follow up with the leader and after 10 seconds, this broker will be removed from ISR.</p><p>The default minimum in-sync replica (min.insync.replicas) is 1. It means that if all the followers go down, then ISR only consists of the leader. Even if ack is set to all, it actually only commits the message to 1 broker (the leader) which makes the message vulnerable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAp9FcFqGL5AdW5yPgFzPQ.png" /></figure><h3><strong>Retries</strong></h3><p>This property determines the maximum number of retries the producer will attempt in case of a transient error before giving up. The default value is 0 (no retries). Set this property to a higher value to enable retries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7ALk7WIApIX5_4EALP0DA.png" /></figure><h3><strong>Retry Backoff Ms</strong></h3><p>This property specifies the time to wait (in milliseconds) between retries. The default value is 100 milliseconds. You can adjust this value to control the delay between retries. For example: props.put(“retry.backoff.ms”, 500).</p><h3><strong>Duplicated Message Case</strong></h3><ul><li>A Producer attempts to write a message to a topic partition.</li><li>The broker does not acknowledge the write due to some transient failure scenario.</li><li>The Producer should retry as it does not know whether the write succeeded or not.</li><li>If the Producer is not idempotent and the original write did succeed then the message would be duplicated.</li></ul><p>To overcome the given message duplication case we can enable the idempotent producer config.</p><h3><strong>Idempotent Producer</strong></h3><p>By configuring the Producer to be idempotent, each Producer is assigned a unique Id (PID) and each message is given a monotonically increasing sequence number. The broker tracks the PID + sequence number combination for each partition, rejecting any duplicate write requests it receives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsFNQjSqE2vX_ow4yLP-aA.png" /></figure><p>To ensure the idempotent behaviour then the Producer configuration acks must also be set to all. The leader will wait until at least the minimum required number of in-sync replica partitions have acknowledged receipt of the message before itself acknowledging the message.</p><p>The recommendation is to leave the retries as the default (the maximum integer value) and limit retries by time, using the Producer configuration delivery.timeout.ms (default = 2 minutes)</p><h3><strong>Sending Messages In Order</strong></h3><p>Another important config to ensure the order is max.in.flight.requests.per.connection, and the default value is 5. This represents the number of unacknowledged requests that can be buffered on the producer side. If the retries is greater than 1 and the first request fails, but the second request succeeds, then the first request will be resent and messages will be in the wrong order.</p><p>To Ensure Message Ordering:</p><ul><li>Need to set retry = INT.MAX</li><li>Max.in.flight.requests.per.connection = 1</li></ul><h3><strong>Batch Size</strong></h3><p>Kafka batch size refers to the maximum amount of data that a Kafka producer can send in a single request. It represents the size of the data batch that is accumulated before it is sent to the Kafka broker.</p><p>When a Kafka producer sends messages to a Kafka broker, it can group multiple messages into a single batch for more efficient data transmission. The batch size determines the threshold at which the producer sends the accumulated messages as a batch.</p><p>The batch.size configuration property in the Kafka producer controls the maximum size of a batch in bytes. By default, the value is set to 16 KB.</p><h3><strong>Linger MS</strong></h3><p>The linger.ms configuration in Kafka producer specifies the amount of time (in milliseconds) that a producer will wait before sending a batch of messages to the Kafka broker. It introduces a delay or pause in the producer’s send operation, allowing it to accumulate more messages and send them as a batch.</p><p>When a producer receives messages to be sent to Kafka, it can either send them immediately or wait for a short period to collect more messages and send them together as a batch. The linger.ms configuration controls this delay or waiting time.</p><p>By default, the linger.ms value is set to 0, indicating that the producer sends messages as soon as possible without any waiting. However, setting a non-zero value introduces a delay, which can be beneficial in scenarios where there is a burst of messages or when optimizing for higher throughput.</p><h3><strong>Batch and Linger.MS Correlation</strong></h3><ul><li>If the accumulated messages reach the batch.size threshold before the linger.ms timeout occurs, the producer will send the batch immediately without waiting for the full linger.ms duration.</li><li>If the linger.ms timeout occurs before the batch.size threshold is reached, the producer will send the accumulated messages as a batch regardless of the batch size.</li><li>In other words, the batch.size is the primary factor that triggers the sending of a batch, while the linger.ms provides an additional timing component that can influence when the batch is sent.</li></ul><h3><strong>Buffer Memory</strong></h3><p>The buffer.memory configuration specifies the total amount of memory available to the producer for buffering outgoing messages before they are sent to the Kafka broker. It represents the maximum amount of memory that the producer can use for storing unsent messages. Configuration value set by bytes and default value is equal to 32mb</p><p>Memory Consumption: The buffer.memory value defines how many messages the producer can hold in memory. Increasing this value allows more messages to be stored in memory but also consumes more memory. Therefore, it is essential to adjust this value considering the available memory capacity of the server and the needs of other applications running on the same machine.</p><p>Performance: The buffer.memory value affects the rate at which the producer sends messages to target partitions. Increasing this value allows the producer to accumulate more messages and create larger batches, leading to higher data transmission rates and better performance. However, setting an excessively high value may increase memory usage and potentially introduce delays.</p><h3><strong>Batch Size And Buffer Memory Correlation</strong></h3><p>Insufficient buffer space: The producer may not have enough buffer memory to accommodate the entire batch of messages specified by batch.size. This can result in buffer overflow, where the producer is unable to buffer all the messages before sending them. In such cases, the producer will be forced to either truncate the batch to fit the available buffer space or fail to produce the messages altogether.</p><p>Increased memory pressure: The producer may experience increased memory pressure if the batch.size is significantly larger than the buffer.memory. This can result in higher memory consumption and potentially impact the overall stability and performance of the producer and the underlying system. It may lead to increased garbage collection activity, memory swapping, or even out-of-memory errors.</p><p>Higher latency and slower throughput: When the batch size exceeds the buffer memory, the producer will need to wait for the buffer to free up space before it can send the batched messages. This can introduce additional latency and reduce the throughput of message production. The producer may have to wait longer for the buffer to become available, which can impact the overall efficiency and responsiveness of the system.</p><h3><strong>MAX BLOCK MS</strong></h3><p>The max.block.ms configuration in Kafka producers determines the maximum amount of time in milliseconds that the send() method can block.</p><p>The max.block.ms configuration specifies the maximum duration the producer is willing to wait for the buffer space or metadata refresh to become available. If the specified time elapses and the producer is still unable to proceed, it will throw a TimeoutException.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342806ceb647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Popular Garbage Collection Algorithms and Go Memory Management]]></title>
            <link>https://medium.com/@alper.baysal./popular-garbage-collection-algorithms-and-go-memory-management-88ebc9a5874?source=rss-b62dd39df4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ebc9a5874</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Alper Baysal]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 20:36:12 GMT</pubDate>
            <atom:updated>2023-07-10T20:36:12.466Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why memory management is so important?</strong></h3><p>When a program runs, various objects are created and stored in memory. However, it is important to release the memory occupied by these objects when they are no longer needed, so that memory usage can be managed efficiently.</p><p>If a program fails to clean up the objects it creates in memory, a series of issues related to the persistence and accumulation of these objects can arise. These may include:</p><ul><li>Memory Leaks</li><li>Performance Issues</li><li>Resource Waste</li><li>Security Vulnerabilities</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smdk-LcST-fGXyx83-1Xsg.png" /></figure><h3>What does garbage collector mean?</h3><p>The Garbage Collector is an automatic memory management mechanism used to manage the usage of dynamically created objects in memory while a program is running.</p><p>When a program runs, various objects are created and stored in memory. However, it is important to release the memory occupied by these objects when they become no longer needed, so that memory usage can be managed efficiently.</p><p>The Garbage Collector performs this task automatically. It detects unused objects in memory and either deletes or releases them automatically. As a result, programmers are relieved from manual memory management and can avoid memory leaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlLW_AXd73FyNJzkWbe14g.png" /></figure><h3><strong>Pause Time And Throughput</strong></h3><p><strong>Pause Time</strong>: The duration it takes for a program to free up memory occupied by objects that have finished their job. During this time, program execution is halted.</p><p><strong>Throughput</strong>: The percentage of time spent on activities other than garbage collection in the overall execution time. Ideally, languages aim for higher throughput. The higher the throughput, the shorter the pauses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhInc_7C4PGwYKLpm6ayOg.png" /></figure><h3><strong>Reference Counting</strong></h3><p>This algorithm maintains a reference count for an object. Whenever a reference is created for an object, the count is incremented, and when a reference is deleted, the count is decremented. Objects with a count of zero are marked as unused and ready for deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9qiVM935Zsq4_zKX9-EHg.png" /></figure><p>Pros:</p><ul><li>Simple and easy to implement.</li><li>Low pause time during garbage collection.</li><li>High efficiency.</li></ul><p>Cons:</p><ul><li>The count can grow large, especially in scenarios with frequent reference creation and deletion.</li><li>If there are pointer cycles within object groups, the count may never reach zero, leading to memory leaks.</li><li>Memory recycling can be costly as freed objects are typically added to a free list.</li></ul><h3><strong>Mark-Sweep Algorithm</strong></h3><p>This algorithm involves a marking phase, used to identify marked objects, and a sweeping phase, used to delete unmarked objects. In the marking phase, live objects are marked. In the sweeping phase, unmarked objects are deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*XTxB9xV8AK3Oivg2.jpg" /></figure><p>Pros:</p><ul><li>It does not impose performance overhead like Reference Counting.</li><li>Properly handles circular reference chains.</li></ul><p>Cons:</p><ul><li>It can lead to memory fragmentation, creating many small gaps and requiring more memory allocation.</li><li>Requires a separate sweeping process to remove marked objects.</li></ul><h3><strong>Copying Algorithm</strong></h3><p>This algorithm divides the memory into two sections: used and unused. Objects in the used memory are marked and copied to the unused memory. During the copying process, the locations of objects are changed, requiring updates to their references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iioFUtKtgkHzV4IEI1O-w.png" /></figure><p>Pros:</p><ul><li>Prevention of fragmentation among objects in memory.</li><li>Efficient utilization of memory space.</li><li>Simple and fast.</li></ul><p>Cons:</p><ul><li>Cost of the copying process.</li><li>Half of the memory becomes unused due to the memory being divided.</li></ul><h3><strong>Tricolor Mark-and-Sweep Algorithm</strong></h3><p>This algorithm performs marking and sweeping of objects by tracking the color state of each object. Three different colors are used: white, gray, and black.</p><p>Initially, all objects are white. Before the processing begins, accessible objects are marked as gray, and objects traversed during the process are marked as black. White objects that reference other objects within black objects are automatically marked as gray. This process is repeated until completion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_i4Sfp1RwNeQVg7WzMbrLw.png" /></figure><h3>Garbage Collector on Go</h3><p>In Go programming language, the Garbage Collector (GC) automatically runs based on the Tricolor Mark and Sweep algorithm.</p><p>Go GC also divides large memory blocks into smaller blocks. This allows for faster and more efficient utilization of smaller memory blocks when they are in use.</p><h3>Memory Monitoring on Go</h3><p><strong>Memstats</strong>: The “runtime.Memstats” library exposes statistics about system memory usage, garbage collection, and more. Using this library, we can track the total number of objects on the heap, which can be used as an indicator of our performance. Therefore, when we start making heap optimizations, we expect to see a decrease in this metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6DtiDmPuMKKin5iKiCIzA.png" /></figure><p><strong>PProf:</strong> The (profiling and tracing) package can be used to generate a heap profile of your program and see which code sections are allocating a large number of heap objects during object allocation. The “pprof” CLI also provides a method to pinpoint the exact code line responsible by stepping through the specific function line by line, allowing us to focus our efforts accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Eq0wp2mP5qXN3n8DvLfRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWQJXEYAAumCxJHvSn3UXg.png" /></figure><h3>How can we optimize our memory on Go?</h3><p><strong>Reducing the number of long-lived objects</strong>: Instead of having objects persist in the heap, they can be created as values instead of references when needed. For example, if we need certain data for each item in a user request, instead of precomputing and storing it for a long time in a cache, we can calculate it per request to reduce the number of objects in the heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nu08pmL0kQDiN8Jn8nq81A.png" /></figure><p><strong>Avoiding holding pointers within pointers</strong>: If we have a reference to an object and that object itself contains more pointers, even if they are embedded, each of them is considered as separate objects in the heap. By modifying the embedded values to not hold pointers, we can reduce the number of objects to be traversed.</p><p><strong>Avoiding unnecessary String/byte arrays</strong>: String/byte arrays are treated as separate objects in the heap since they are handled as pointers behind the scenes. If possible, try to represent them with non-pointer values like integers/floats for numeric values or types like time.Time for dates. This can help reduce the number of objects in the heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*4x1TPP90t7xWgzeB7iYmWQ.png" /></figure><p><strong>Object Pooling</strong>: If our program needs to create multiple instances of the same object, we can use object pooling to reduce the creation cost of these objects. However, it’s important to note that the Garbage Collector won’t work on objects inside the pool, so it’s necessary to clean up these objects when they are no longer in use. Otherwise, it can lead to memory leaks.</p><p><strong>Cleaning up unused fields</strong>: In Go, basic types contain default values (e.g., Bool -&gt; false, int -&gt; 0) by default. These values occupy memory even if we don’t use those fields. Cleaning up unused fields within the project helps reduce memory usage.</p><p><strong>Moving data out of the heap</strong>: By removing data from the heap, we significantly reduce the amount of work the Garbage Collector needs to perform. One option is to move the data to an external resource. It’s important to consider the additional overhead of making requests to retrieve data from this external resource.</p><p>Another option is to leverage an open-source Go package that allows storing data outside the heap but still within the system memory. An example of such a package is “go-offheap”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZOUJKDxWNwXRDt0EWb56A.png" /></figure><p><strong>Sorting Structs by Memory Usage</strong>: Go’s memory allocator does not rearrange the data structure of structs to optimize memory usage. However, we can reduce memory usage by organizing these fields in a way that they can share memory blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*Tjkg-19io8EjntyuezLr4w.png" /><figcaption>GoodObject: 16 bytes, BadObject: 24 bytes</figcaption></figure><p>By arranging the structs in this manner, we can achieve more efficient memory utilization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ebc9a5874" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Locks on Programming]]></title>
            <link>https://medium.com/@alper.baysal./locks-on-programming-f4316bbdeebf?source=rss-b62dd39df4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4316bbdeebf</guid>
            <category><![CDATA[optimistic-locking]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alper Baysal]]></dc:creator>
            <pubDate>Fri, 13 May 2022 07:13:46 GMT</pubDate>
            <atom:updated>2022-05-13T07:13:46.212Z</atom:updated>
            <content:encoded><![CDATA[<p>When we have a multithread process or multi instance applications that share the same resources such as database, it is hard to maintain the integrity and the correctness of the data. That is where the Locks came to our help. In the most basic form, Lock is a restrictor policy that regulates access to shared resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9sqGTGmbYliZpd1f4bK4A.png" /><figcaption>Image Source: <a href="https://web.mit.edu/6.005/www/fa15/classes/23-locks/">Link</a></figcaption></figure><p>The example above shows the real problem. When a cash machine tries to deposit an amount of cash to an account the processes are simple. Get the current account balance, add deposit amount to the balance, and update the account current balance with the newly calculated one. But if you look at the picture again you will see two different atm is trying to deposit on a same account. Depending on the milliseconds and the calculating duration on the atm clients Account 1 Balance can be $150 or $250.</p><p>We can solve this problem with a lock for each bank account. The first ATM that access and obtain the lock can make some changes on the current balance. The other ATMs that tries the access the same account can’t obtain the lock therefore have to wait the lock to be released by the first owner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*F5SMBR_lt_R-I7hlwxlvPw.png" /><figcaption>Image Source: <a href="https://web.mit.edu/6.005/www/fa15/classes/23-locks/">Link</a></figcaption></figure><p>In this article I will be trying to give you some perspective about -Optimistic- and -Pessimistic- Locking methods.</p><h3><strong>Optimistic Locking</strong></h3><p>With optimistic locking we trust that multiple applications use same data without a lock and everything is going to be alright. I know that sounds a little suspicious when we first read it but there is a catch. We don’t use Lock with Optimistic Locking but we use version or timestamp for the data that will be shared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*ZK3rgIYNLzVgW0lx0KD4Aw.png" /><figcaption>Image Source: <a href="https://enterprisecraftsmanship.com/posts/optimistic-locking-automatic-retry/">Link</a></figcaption></figure><p>Let’s assume that untouched data’s first version is “1”. The first application instance obtain the data and make some changes on it. Before rewrite the original data with new one we have, we should check the original data’s version. If it’s in the same version when we first acquire, that means no other application changed that particular data and it is safe to rewrite. Now the data’s version in the source is “2”. But what if the version is different than our current version in hand, then all process have to start over from the beginning.</p><p>We can also use timestamp (last modified) instead of version column. In fact we can implement Optimistic Locking without timestamp or version, but we have to check the every field on the data and make sure nothing is different than what we have in hand.</p><h3><strong>Pessimistic Locking</strong></h3><p>Unlike Optimistic Locking, there is an actual lock system in the Pessimistic Locking. As soon as one application starts to update a data, places a lock on it. Other applications which tries to update the same data have to wait the first one to remove the lock. Only then others makes changes on the same data. Therefore we can prevent simultaneous changing request on the shared data. But there is one thing we need to consider while using Pessimistic Lock, Deadlock. Let’s assume one user get the data and put a lock on that row on the database. While doing some calculations and modifications on it application crashes and process never finished. The crashed application will never be able to release the lock on the data and therefore other applications never access that data. To prevent this situation/deadlock we can use timeout for locks. Even if application never release the lock on the data, whenever the timeout duration is passed the lock release automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfnJU_klmBTGqK2u8A-AFw.png" /></figure><h3>Conclusion</h3><p>So, it is conclusion time. Both optimistic and pessimistic locking are helpful techniques in programming. Optimistic locking is more suitable when you don’t expect many collisions. It costs less to do a normal operation but if the collision DOES occur you would pay a higher price to resolve it as the transaction is aborted. Pessimistic locking is more suitable when a collision is anticipated. So when collisions happen the transactions which would violate synchronization are simply will be blocked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4316bbdeebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>