<?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 erhan355 on Medium]]></title>
        <description><![CDATA[Stories by erhan355 on Medium]]></description>
        <link>https://medium.com/@erhan355?source=rss-27904bb845f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*P5XU7iohDBU2OVm_.jpg</url>
            <title>Stories by erhan355 on Medium</title>
            <link>https://medium.com/@erhan355?source=rss-27904bb845f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:56:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erhan355/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[Designing an E-Commerce Checkout System]]></title>
            <link>https://medium.com/@erhan355/designing-an-e-commerce-checkout-system-9e5ad5b8de47?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5ad5b8de47</guid>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 20:37:52 GMT</pubDate>
            <atom:updated>2026-07-06T20:37:52.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Problem Definition and Requirements</h3><p>When a customer confirms a cart, the system must answer several questions reliably: Is the cart still valid? Is the stock available? Can we charge the customer? Can the order be prepared? Can the customer see the latest status? and etc..</p><p>The aim is not to lock the whole business process inside one large transaction. That would be too slow, too fragile, and not realistic once each service owns its own data. A better goal is to let every service make a local, durable decision and then coordinate the flow through well-defined events.</p><p>To my mind,It is always easier to define functional requirements than defining non functional requirements.</p><p>Actually, everyone can easily list the functional requirements in one go, so I’d like to focus on the non-functional requirements instead.</p><h3>Non-functional expectations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSEwJI8qeZixJP6clytLcw.png" /></figure><h3>Key difficulties</h3><p>· There is no single ACID transaction across Order, Inventory, Payment, and Warehouse services.</p><p>· A payment can succeed while the next step fails, or stock can be reserved while payment fails.</p><p>· Different services may temporarily report different versions of the truth.</p><p>· A service or consumer may crash after writing to its database but before publishing the next event.</p><p>· A naive retry strategy can accidentally turn a small timeout into a duplicate business operation.</p><h3>2. The Transaction Problem in Microservices</h3><p>In a monolithic application, checkout can often be modeled as one database transaction. The system updates inventory, inserts the order, records the payment attempt, and commits everything together. It is easy to reason about because the database is the main source of truth and the transaction boundary is clear.</p><p>In a microservice architecture, that boundary disappears. The Order Service, Inventory Service, and Payment Service usually have separate databases. Forcing them into a single distributed transaction is possible in theory, but in practice it introduces coupling, operational complexity, and failure modes that most modern architectures try to avoid.</p><h3>CAP perspective</h3><p>Distributed data stores can simultaneously provide at most two of three guarantees: <strong>C</strong>onsistency (all nodes see the same data), <strong>A</strong>vailability (every request receives a response), and <strong>P</strong>artition Tolerance (the system continues to operate despite network failures)</p><p>Partition Tolerance cannot be ignored in a distributed system. User-facing commerce systems also care deeply about availability. That usually leaves us with an AP-leaning design where services remain available and converge through events.</p><h3>3. Overall Architecture Approach</h3><p>A first design usually starts with the Order Service calling every downstream service synchronously: reserve inventory, charge payment, notify warehouse, then send confirmation.</p><h3>Limits of a synchronous-first design</h3><p>· Services become<strong> tightly coupled</strong> to each other’s latency and availability.</p><p>· <strong>Failures propagate</strong> through the call chain and can become cascading failures under load.</p><p>· Retry behavior becomes dangerous unless every operation is <strong>idempotent</strong> from the beginning.</p><h3>Moving to event-driven coordination</h3><p>A more resilient design accepts the checkout request, persists the initial order state, and publishes an event to a <strong>broker such as Kafka</strong>.</p><p>Downstream services consume events, do their local work, and publish their result events. The Order Service then updates the Saga state and decides the next step.</p><p>The client can receive a response such as 202 Accepted. <em>This does not mean the order is fully completed</em>. It means the platform accepted the request and the workflow is now moving asynchronously. The customer should be able to poll or subscribe to the order status while the Saga progresses.</p><h3>4. Saga Pattern: Orchestration and Choreography</h3><p>A Saga splits a long business transaction into smaller local transactions. Each local transaction commits inside one service. If a later step fails, the system does not roll back through a database transaction; it runs compensating business actions.</p><p>I won’t dive into details of Orchestration and Choreography patterns here but simply ;</p><p>In orchestration, one component coordinates the flow.In this checkout design, that role naturally fits the Order Service. It knows the current order state, publishes commands or events for the next step, waits for result events, handles timeouts, and starts compensation when needed.</p><p>In choreography, there is no central coordinator. Each service listens to events and decides what to publish next. For example, Inventory Service reacts to OrderCreated, then Payment Service reacts to InventoryReserved, and Warehouse reacts to PaymentCompleted.</p><p><strong>Recommended choice for checkout<br></strong>For checkout, I would choose orchestration. The order is the business object the customer and support teams care about, so it is useful to keep the lifecycle visible from the Order Service.</p><p>Choreography is still valid for simpler flows, but once payment, inventory, warehouse, timeout, and cancellation rules are included, orchestration is easier to operate.<br>Orchestration is easier to debug/inspect however coordinator also becomes single point of failure. Trade-off again :(</p><h3>5. Idempotency and Concurrency Controls</h3><p>Idempotency <strong>is not a nice-to-have</strong> in checkout.It is <strong>must</strong>.<br>Customers double-click buttons, browsers retry requests, mobile networks drop connections, and payment providers time out. The backend must assume that the same business request can arrive more than once.</p><h3>5.1 Idempotency key</h3><p>Before sending the checkout request, the client generates an idempotency key and sends it in a header such as Idempotency-Key. The Order Service checks a<strong> fast store such as Redis</strong>. If the key was already processed, the service returns the cached response instead of creating a new order.</p><p>Example Flow</p><pre>key = request.headers[&quot;Idempotency-Key&quot;] <br>cachedResponse = redis.get(key) <br>if cachedResponse exists: <br>return cachedResponse <br>order = createOrder(request.body) <br>response = { &quot;orderId&quot;: order.id, &quot;status&quot;: order.status } <br>redis.set(key, response, ttl = 24 hours) <br>return response</pre><h3>5.2 Database-level guardrails</h3><p>Request-level idempotency is useful, but it should not be the only protection. Two requests for the same cart may still race. A database constraint such as a unique active order per cart is a simple second layer of defense.<br>For example:</p><pre>POST /api/v1/orders/checkout<br>Idempotency-Key: key-abc<br>POST /api/v1/orders/checkout<br>Idempotency-Key: key-def</pre><p>Both requests may refer to the same cart. Since the idempotency keys are different, Redis may treat them as different operations. Without an additional guardrail, two active orders could be created for the same cart.</p><p>A database constraint can provide a second layer of protection.</p><p>Simple example:</p><pre>UNIQUE(cart_id, status)</pre><p>A better option is often a partial unique index for active states only:</p><pre>CREATE UNIQUE INDEX unique_active_order_per_cart<br>ON orders(cart_id)<br>WHERE status IN (&#39;CREATED&#39;, &#39;PENDING_PAYMENT&#39;, &#39;RESERVED&#39;);</pre><p>For example, this is allowed:</p><pre>cart_id    status<br>--------   ----------<br>CART-123   COMPLETED<br>CART-123   CANCELLED</pre><p>But this should not be allowed:</p><pre>--------   ----------<br>CART-123   PENDING_PAYMENT<br>CART-123   RESERVED</pre><p>If the application tries to insert another active order for the same cart, the database rejects it:</p><pre>INSERT INTO orders(cart_id, status) VALUES (&#39;CART-123&#39;, &#39;PENDING_PAYMENT&#39;);</pre><h3>5.3 Distributed lock</h3><p>A short-lived distributed lock can be added when concurrency is high. The lock prevents multiple workers from processing the same cart at the same time. Still, a lock is only a helper. The database constraint remains the final guardrail because locks can expire, be misconfigured, or fail during network problems.</p><p>For example, two workers may try to process the same cart:</p><pre>Worker-1 -&gt; checkout for CART-123<br>Worker-2 -&gt; checkout for CART-123</pre><p>A Redis lock can be used:</p><pre>SET lock:checkout:CART-123 worker-1 NX EX 30</pre><p>With this approach, only one worker can process the cart at a time:</p><pre>Worker-1 -&gt; lock acquired<br>Worker-2 -&gt; lock failed</pre><h3>6. Data Model</h3><p>The data model is more than a list of tables. It defines where the platform stores lifecycle state, reservation state, payment state, and event history. This matters because recovery depends on being able to reconstruct what happened after a crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kusdZjQ6GXba-qoW4b079A.png" /></figure><h3>Inventory reservation model</h3><p>For stock, <strong>reserving first</strong> is usually <strong>safer </strong>than immediately reducing final stock. If payment <strong>fails</strong>, the reservation is <strong>released</strong>. If payment succeeds, the reservation is converted into a committed sale. This makes compensation explicit and keeps the customer experience predictable.</p><h3>Outbox and event history</h3><p>The Outbox Pattern is important because a service may write to its database and crash before publishing the event. With an outbox, the service writes the business state and the event record in the <strong>same local transaction</strong>. A <strong>separate publisher</strong> then reliably sends the event to Kafka.</p><h3>7. API and Event Contracts</h3><p>The API defines how clients ask the platform to do something. The event contract defines how services explain what has happened inside the platform.</p><p><strong>Suggested API shape</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdbxlfHXu1ydpE2hj1fzVQ.png" /></figure><p><strong>Typical checkout events</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8uCASI46WL4R6MPWo73TA.png" /></figure><h3><strong>8. Failure Handling and Recovery</strong></h3><h4>8.1 Persist Saga state</h4><p>We can use an event store database for this purpose. Instead of keeping only the latest Saga state, each important action can be stored as an event. For example, events such as ORDER_CREATED, PAYMENT_RESERVED, STOCK_RESERVED, PAYMENT_CONFIRMED, or ORDER_CANCELLED can be written to the event store.</p><p>If the Order Service crashes or restarts, it can read the stored events and rebuild the current Saga state. Based on the last successful event, the service can decide whether to continue the next step or trigger compensation.</p><p>Note : The Event Store is <strong>often used together with the Outbox Pattern</strong>. This means the event is <strong>first written to the database</strong>, and <strong>then published to Kafka.</strong></p><p>This approach solves the following problem:The order was written to the database, but the service crashed before the Kafka event could be published.</p><h4><strong>8.2 Timeout and stuck Saga handling</strong></h4><p>A Saga should not remain in the same step indefinitely. If a step takes longer than the expected time window, the system should treat it as a separate failure scenario and make a controlled decision.</p><p>For example, if inventory has already been reserved but the payment process does not complete within the allowed time, the system should either release the reserved stock or move the order into a manual review state. This prevents stock from being locked forever and keeps the order lifecycle predictable.</p><p>In distributed systems, leaving a Saga in a pending state forever is usually more dangerous than failing it explicitly. A timeout mechanism helps the system recover safely, trigger compensation when needed, and avoid hidden operational problems.</p><h4><strong>8.3 Retry, DLQ, and observability</strong></h4><p>Retries should use exponential backoff and a maximum attempt count. Poison messages should move to a dead-letter queue, not loop forever. Every event and log line should carry order_id and correlation_id so that the full checkout story can be traced across services.</p><h3>9. Scaling and Optimization</h3><h3>9.1 Horizontal Scaling for Services</h3><p>At the beginning, each service may run as a single instance. As traffic increases, a single Order Service or Inventory Service may no longer be enough. In that case, we can place a<strong> load balancer </strong>in front of each service and run multiple instances of the same service.</p><p>The goal is to scale each service independently.</p><p>For example, if the Order Service receives too much traffic, only the Order Service instances can be increased. If the Payment Service becomes slow, only the Payment Service can be scaled. This way, we do not need to scale the entire system at the same time.</p><p>When scaling services horizontally, critical state should not be stored only in memory. Order status, payment status, reserved stock, and Saga state should be stored in a durable database. This allows service instances to restart or scale without losing checkout progress.</p><h3>9.2 Database Sharding</h3><p>In many checkout systems, the most critical bottleneck appears at the database layer. Scaling services is usually easier than scaling a database. If all writes still go to a single database, the system can become slow even if there are many service instances.</p><p>Sharding means splitting data across multiple databases or nodes instead of keeping everything in one large database. For example, the orders table can be divided by user_id.</p><pre>user_id 1-100000       -&gt; Shard 1<br>user_id 100001-200000  -&gt; Shard 2<br>user_id 200001-300000  -&gt; Shard 3</pre><p>With this approach, all order data is not stored on a single database node. The data and the load are distributed across multiple shards.</p><p>Some technologies provide built-in sharding or strong sharding support:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bgjus5OOPk5jVGYujNSgSw.png" /></figure><p>For example, a simple Citus-based setup may look like this:</p><pre>10.0.0.10 -&gt; Citus Coordinator Node<br>10.0.0.11 -&gt; Citus Worker Node 1<br>10.0.0.12 -&gt; Citus Worker Node 2</pre><p>The application connects to the coordinator node. The coordinator keeps metadata about where the data is located and routes queries to the correct worker nodes. The worker nodes store the actual distributed data.</p><h3>9.3 Application-Level Sharding</h3><p>In application-level sharding, the application code decides which shard should be used.</p><p>For example, the application may route users to shards based on user_id:</p><pre>user_id % 3 = 0 -&gt; Shard 1<br>user_id % 3 = 1 -&gt; Shard 2<br>user_id % 3 = 2 -&gt; Shard 3</pre><p>The advantage of this approach is control. The application owns the routing logic and can decide how data should be distributed.</p><p>The disadvantage is complexity. Routing, resharding, cross-shard queries, backups, and monitoring become harder.</p><p>For example, if the shard is selected by user_id, but the system only has order_id, finding the correct shard may become difficult.</p><p>This is why shard key selection is very important.</p><h3>9.4 Shard Key Selection</h3><p>The shard key determines how data is distributed across shards. If the shard key is chosen incorrectly, the system may not scale well.</p><p>A good shard key should:</p><ul><li>distribute data evenly,</li><li>send common queries to a single shard when possible,</li><li>avoid hot shards.</li></ul><p>For example, sharding by user_id can be useful for customer order-history queries because most orders for the same user are stored together. However, very active users may create hot shards.</p><p>Sharding by order_id may distribute writes more evenly, but reading all orders for a specific user may require querying multiple shards.</p><p>The best shard key depends on the dominant access pattern of the system.</p><h3>9.5 Kafka Partitioning</h3><p>A checkout system is often event-driven, so Kafka must also be scaled carefully.</p><p>The main goal is to keep all events for the same order in the same Kafka partition. This can be done by using order_id as the Kafka message key.</p><pre>order_id = 1001 -&gt; Partition 0<br>order_id = 1002 -&gt; Partition 1<br>order_id = 1003 -&gt; Partition 2</pre><p>Kafka preserves ordering inside a partition. This is important for Saga-based checkout flows because events for the<strong> same order should be processed in the correct sequence</strong>.</p><p>For example:</p><pre>OrderCreated<br>InventoryReserved<br>PaymentCompleted<br>OrderConfirmed</pre><p>These events should not be processed in a random order for the same order.</p><p>However, partition count must be planned carefully. If there are too few partitions, increasing the number of consumers will not increase parallelism after a certain point. For example, if a topic has 3 partitions, only 3 consumers in the same consumer group can actively process that topic in parallel.</p><p>So Kafka scaling depends on both partition count and consumer count.</p><h3>9.6 Caching</h3><p>Caching can reduce database load for read-heavy data, but it should not be used blindly in the checkout flow.</p><p>Cart reads, product display data, and order-status reads are good candidates for caching. These are frequently read and do not always require a database query on every request.</p><p>Inventory data is more sensitive. If inventory cache is kept for too long, the system may show incorrect stock information. For example, keeping stock data in cache for one hour can cause users to see products as available even after they are sold out.</p><p>Because of this, stock cache should have a short TTL. More importantly, the final stock reservation should not rely only on cache. During checkout, the final reservation must be confirmed by the Inventory Service and the database.</p><h3>9.7 Read Replicas</h3><p>Read replicas can reduce load on the primary database for read-heavy operations.</p><p>For example, order history, reporting screens, customer support queries, and admin dashboards can read from replicas instead of the primary database.</p><p>However, the main checkout write path should still go through the primary database. Operations such as creating an order, reserving stock, updating payment status, and storing Saga state require strong consistency and clear transaction rules.</p><h3>10. Trade-off Evaluation</h3><p>Checkout is a revenue-critical flow, so ambiguity is expensive. The design should make it clear where we accept eventual consistency, where we require local consistency, and how we recover when the workflow is interrupted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLSFEoGEBHpWQC3CAJ9eAw.png" /></figure><p>For a smaller platform, a modular monolith may still be the better first architecture. The Saga design starts paying off when independent scaling, team ownership, and failure isolation are more valuable than the simplicity of a single transaction boundary.</p><h3>11. Final Thoughts</h3><p>The design in this article is not the only way to build a checkout system. It is useful when the flow contains multiple steps such as inventory reservation, payment processing, order confirmation, notification, fraud detection, and compensation.</p><p>However, not every system needs a fully event-driven Saga architecture. For simple services, synchronous REST or gRPC calls may still be enough because they are easier to understand, test, and operate.</p><p>There are also different ways to implement distributed workflows. Some teams prefer choreography, where services react to events without a central coordinator. Others prefer orchestration, where a dedicated orchestrator controls the Saga steps. Some teams use workflow engines such as Temporal to manage retries, timeouts, state transitions, and compensation logic more explicitly.</p><p>In smaller systems, teams may avoid the Saga Pattern completely and use synchronous calls with retry, timeout, and circuit breaker mechanisms. This can be acceptable when the business flow is simple and the failure scenarios are limited.</p><p><strong>Debezium can improve reliability when Kafka and the Outbox Pattern are used together.</strong> Instead of publishing events directly from application code after a database write, the service writes the business data and the outbox event in the same database transaction. <strong>Debezium then reads the database change log and publishes the event to Kafka.</strong> This reduces the risk of the database and Kafka becoming inconsistent.</p><p>In the end, the right design depends on the complexity of the checkout flow, the expected traffic, the consistency requirements, and the team’s operational experience.</p><p><em>A good checkout architecture should not only complete successful orders, but also handle failures, retries, timeouts, and compensation in a controlled way.</em></p><h3>References</h3><p><a href="https://towardsdev.com/building-an-e-commerce-checkout-system-distributed-transactions-saga-patterns-and-reliability-44743ae650d6">https://towardsdev.com/building-an-e-commerce-checkout-system-distributed-transactions-saga-patterns-and-reliability-44743ae650d6</a></p><p><a href="https://www.reddit.com/r/softwarearchitecture/comments/1kufyms/eli5_cap_theorem_in_system_design/">https://www.reddit.com/r/softwarearchitecture/comments/1kufyms/eli5_cap_theorem_in_system_design/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5ad5b8de47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tactical DDD Explained with a Ticket Entity Example]]></title>
            <link>https://medium.com/@erhan355/tactical-ddd-explained-with-a-ticket-entity-example-62998eb7aebd?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/62998eb7aebd</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[domain-driven]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Thu, 28 May 2026 15:34:04 GMT</pubDate>
            <atom:updated>2026-05-28T15:34:04.742Z</atom:updated>
            <content:encoded><![CDATA[<p>In the simplest terms, Tactical DDD (Domain-Driven Design) is about putting business rules inside domain objects instead of scattering them across services and handlers (CQRS handlers, application services, etc.).</p><p>The main idea is simple:</p><blockquote><em>We create domain objects that protect their own rules and state transitions.</em></blockquote><p>Typical Tactical DDD building blocks include:</p><ul><li>Entities</li><li>Value Objects</li><li>Aggregate Roots</li><li>Domain Events</li><li>Repositories</li><li>Factory Methods</li></ul><h3>Anemic Model</h3><p>An anemic model is when an entity has data but no behavior.</p><p>A lot of projects end up with entities like this:</p><pre>public class Ticket<br>{<br>    public TicketStatus Status { get; set; }<br>}</pre><p>And then somewhere else:</p><pre>if (ticket.Status == TicketStatus.Available)<br>{<br>    ticket.Status = TicketStatus.Reserved;<br>}</pre><p>At first, this looks harmless.</p><p>But over time, business rules start spreading across handlers and services. The entity becomes just a database container instead of a real domain object.</p><p><strong>A More DDD-Oriented Ticket Entity</strong></p><p>n Tactical DDD, the entity encapsulates its state and does not allow anyone to modify it directly.</p><p>Something like this:</p><pre>public TicketStatus Status { get; private set; }</pre><p>This small detail changes a lot.Now external code cannot do this:</p><pre>ticket.Status = TicketStatus.Confirmed;</pre><p>The only way to change the state is through domain methods like:</p><pre>ticket.Reserve(userId);<br>ticket.Confirm(userId);<br>ticket.Cancel();</pre><p>That’s where Tactical DDD starts becoming visible.</p><p>Now the entity effectively becomes a small state machine.</p><h3>State Machine</h3><p>The ticket transitions become very clear:</p><pre>Available  -&gt; Reserved<br>Reserved   -&gt; Confirmed<br>Reserved   -&gt; Available<br>Confirmed  -&gt; Cancelled</pre><p>And the domain methods map directly to those transitions:</p><pre>Reserve()<br>Confirm()<br>Release()<br>Cancel()</pre><p>This makes the business flow much easier to understand.</p><p>Even someone unfamiliar with the codebase can quickly understand how tickets behave.</p><h3>Rich Domain Model vs Service-Heavy Logic</h3><p>One of the biggest ideas behind Tactical DDD is the concept of a Rich Domain Model.</p><p>That simply means:</p><p><em>Entities should contain behavior, not just data.</em></p><p>So instead of handlers making business decisions like this:</p><pre>if (ticket.Status == TicketStatus.Reserved)<br>{<br>    ticket.Status = TicketStatus.Confirmed;<br>}</pre><p>The handler simply delegates behavior to the domain:</p><pre>ticket.Confirm(userId);</pre><p>This is a huge architectural difference.</p><p>The application layer orchestrates.</p><p>The domain layer enforces rules.</p><p>That separation keeps the system cleaner and easier to maintain as it grows.</p><h3>Factory Methods Also Help</h3><p>This entity also uses a factory method:</p><pre>public static Ticket Create(<br>    Guid eventId,<br>    string seat,<br>    decimal price)<br>{<br>    return new Ticket(eventId, seat, price);<br>}</pre><p>This helps centralize object creation.</p><p>Instead of letting callers create half-valid entities, the domain controls how a ticket starts its lifecycle.</p><p>For example:</p><ul><li>Status always starts as Available</li><li>Timestamps are initialized correctly</li><li>Validation can happen immediately</li></ul><p>Again, this is a very common pattern in Tactical DDD.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62998eb7aebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Notes On Indexing]]></title>
            <link>https://medium.com/@erhan355/my-notes-on-indexing-a853ee3e9ebc?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a853ee3e9ebc</guid>
            <category><![CDATA[index]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 22:35:13 GMT</pubDate>
            <atom:updated>2026-03-03T22:35:13.343Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s how I explain them to myself in the simplest way possible.</p><p>An index is like making a separate, well-organized phone book,It’s not changing the original table.</p><p>The Performance Problem Indexes Solve</p><pre>CREATE TABLE test_table (<br>    id   NUMBER PRIMARY KEY,<br>    x    NUMBER,<br>    y    NUMBER,<br>    fruit VARCHAR2(20),<br>    colour VARCHAR2(20)<br>);<br>-- ... populated with 10M realistic rows</pre><p>A simple equality lookup:</p><pre>SELECT * FROM test_table WHERE id = 1234567;</pre><p><strong>Without any index</strong> → the database performs a <strong>full table scan</strong>: it reads all 10 million rows sequentially.</p><p>Execution time: ~0.486 seconds</p><p>Now create a basic index:</p><pre>CREATE INDEX index_test_table_id ON test_table(id);</pre><p>Run the same query again → execution time drops to <strong>~0.016 seconds</strong> (~30× faster). (Those are not the exact values ,query time belongs to many factors)</p><p>When you create an index on a column (or several), <strong><em>the database doesn’t modify the table itself.</em></strong></p><p>Instead it builds a completely separate <strong>B-tree structure</strong>:(Simplified to grasp logic)</p><ul><li>Each entry contains:</li><li>The value from the indexed column(s)</li><li>A pointer (row ID / physical location) <strong>to the actual row in the table</strong></li><li>The tree is <strong>balanced</strong> → every path from root to leaf has the same length → logarithmic lookup time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*EMI96wwfjv91BIz3clteGg.png" /></figure><p>Let’s say we want to find value 5 in this tiny B-tree:</p><ol><li>Start at root node [3, 5, 6]</li><li>5 &gt; 3 → go right</li><li>5 == 5 → match found</li><li>Follow the pointer → fetch the real row from disk</li></ol><p><strong>Total operations</strong>: ~3 disk reads (root → leaf → table row).</p><p>Compare to full table scan: potentially millions of reads until the row is found.</p><p>That’s why indexes give such dramatic speedups on selective lookups.</p><p><strong><em>Indexes aren’t free:</em></strong></p><ul><li><strong>INSERT</strong> → new value must be inserted into the correct position in every index → minor overhead (tree stays balanced)</li><li><strong>UPDATE</strong> → treated as DELETE old value + INSERT new value in the index</li><li><strong>DELETE</strong> → remove entry + possible rebalancing (slightly more expensive)</li></ul><p><strong>Composite (Multi-Column) Indexes</strong></p><p>You can index multiple columns:</p><pre>CREATE INDEX idx_id_x ON test_table(id, x);<br><br><br>SELECT WHERE id = 100 AND x = 400     -- uses index<br>SELECT WHERE x = 400                  -- full table scan</pre><p><strong>When Indexes Are Not Used (Common Gotchas)</strong></p><ul><li><strong>Functions on the column</strong></li></ul><p><em>WHERE MOD(id, 4) = 1</em> → cannot seek → full scan Fix: create a function-based index CREATE INDEX ON test_table(MOD(id,4))</p><ul><li><strong>Low selectivity / low cardinality</strong></li></ul><p>If a column has only 4 distinct values (e.g. colour: red, green, blue, yellow) in 10M rows → index rarely helps (still returns millions of rows)</p><ul><li><strong>LIKE with leading wildcard</strong></li></ul><p>WHERE name LIKE ‘%smith’ → cannot use normal B-tree index</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a853ee3e9ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Elasticsearch: The Journey of a Document from RAM to Disk]]></title>
            <link>https://medium.com/@erhan355/inside-elasticsearch-the-journey-of-a-document-from-ram-to-disk-833e7843ea7a?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/833e7843ea7a</guid>
            <category><![CDATA[elastic-stack]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[elastic]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 22:33:40 GMT</pubDate>
            <atom:updated>2026-02-12T22:33:40.195Z</atom:updated>
            <content:encoded><![CDATA[<p>In Elasticsearch, a data’s journey is much more than a simple “save” operation. In this post, we will examine exactly how data is processed within a single shard and what happens behind the scenes during a search.</p><h3>1. The First Step: Buffer and Translog (Write Guarantee)</h3><p>Let’s assume a simple setup: a single instance and a single shard. Imagine we send the following three documents:</p><p>JSON</p><pre>{&quot;id&quot;: 1, &quot;msg&quot;: &quot;Login success&quot;}<br>{&quot;id&quot;: 2, &quot;msg&quot;: &quot;Add to cart&quot;}<br>{&quot;id&quot;: 3, &quot;msg&quot;: &quot;Payment failed&quot;}</pre><p>At this stage, two operations happen simultaneously:</p><ul><li><strong>In-memory Buffer (RAM):</strong> These 3 documents enter the shard’s temporary memory area.</li><li><strong>Translog (Disk):</strong> Simultaneously, this data is appended to a physical file on the disk called the <strong>Translog</strong>.</li></ul><p><strong>The Golden Rule:</strong> For Elasticsearch to return a “200 OK” (Acknowledged) to the client, the data <strong>must</strong> be successfully written to the Translog on the disk.</p><blockquote><strong><em>Search Test:</em></strong><em> If you run </em><em>GET /logs/_search right now, you will get </em><strong><em>0 results</em></strong><em>. Why? Because the data is only in the buffer and is not yet &quot;searchable.&quot;</em></blockquote><h3>2. The Refresh Process: Making Data Visible</h3><p>When the default 1-second interval passes (or you trigger a manual _refresh), the following occurs:</p><ul><li>The <strong>In-memory Buffer</strong> is emptied.</li><li>A Lucene file named <strong>“Segment_1”</strong> is created from these 3 documents.</li><li>This segment is written to the <strong>File System Cache</strong> (the part of RAM managed by the Operating System), not directly to the physical disk.</li></ul><p><strong>Result:</strong> The data is now “searchable,” but it hasn’t been permanently “carved” into the physical disk plates yet.</p><h3>3. New Data and New Segments</h3><p>Now, imagine two more documents arrive immediately after:</p><ul><li>{&quot;id&quot;: 4, &quot;msg&quot;: &quot;Logout&quot;}</li><li>{&quot;id&quot;: 5, &quot;msg&quot;: &quot;Login success&quot;}</li></ul><p>When a refresh happens again, a new file named <strong>“Segment_2”</strong> is created, containing only these 2 documents.</p><p><strong>Current State:</strong> Our shard now contains 2 segments: <strong>Segment_1</strong> (3 docs) and <strong>Segment_2</strong> (2 docs).</p><blockquote><strong><em>Remember:</em></strong><em> Every time a refresh occurs, whatever is in the buffer (whether it’s 1 doc or 100,000) is bundled into a single package and sealed as a new segment.</em></blockquote><h3>4. Persistence: Flush and Lucene Commit</h3><p>Until a <strong>Flush</strong> operation occurs (defaults- triggered every 30 minutes or when the translog hits 512 MB), those segments are essentially just RAM blocks at the mercy of the OS. When a Flush command is triggered:</p><ol><li><strong>Lucene Commit:</strong> The data in the File System Cache is forcibly written to the physical disk using fsync.</li><li><strong>Translog Clear:</strong> Since the data is now safely stored in permanent disk segments, the “backup log” is no longer needed, and the Translog is deleted.</li></ol><h3>5. Hybrid Search: A Step-by-Step Query Process</h3><p>Consider this scenario:</p><ul><li><strong>Segment_1 (On Disk):</strong> Previously written and flushed.</li><li><em>Doc 1:</em> “error log”</li><li><em>Doc 2:</em> “system error”</li><li><strong>Segment_2 (RAM / FS Cache):</strong> Freshly refreshed, not yet flushed.</li><li><em>Doc 3:</em> “critical error”</li></ul><p><strong>When a user searches for the word “error”:</strong></p><ol><li><strong>Shard Query:</strong> Elasticsearch goes to all “live” segments in the shard.</li><li><strong>Hybrid Scanning:</strong></li></ol><ul><li><strong>Segment_1 (Disk):</strong> The OS pulls this index into RAM (if not already cached) and finds “error”. Results: <strong>[1, 2]</strong></li><li><strong>Segment_2 (RAM):</strong> Since this is already in the FS Cache, it is scanned at lightning speed. Result: <strong>[3]</strong></li></ul><p><strong>3. Merging Results:</strong> The shard collects the ID lists: <strong>[1, 2, 3]</strong>..</p><p><strong>4. Scoring:</strong> Relevance is calculated to see which “error” is most important.</p><p><strong>5. Fetching Data:</strong> Once IDs are set, the original JSON content (_source) is read from the respective segment files and sent to the user.</p><h3>6. The Secret of Performance: Why is it so fast?</h3><h3>A. Term Index is in RAM</h3><p>Every segment has an <strong>Inverted Index</strong>. Elasticsearch keeps a tiny summary of this called a <strong>“Term Index”</strong> directly on the <strong>JVM Heap (RAM)</strong>. When you search, it checks this summary first. If “error” doesn’t exist in 900 out of 1000 segments, it doesn’t even touch those files.</p><h3>B. Segment Merge (The Housekeeper)</h3><p>Having too many small segments slows down performance. The background <strong>Merge Process</strong> constantly watches these and combines smaller segments into fewer, larger ones to keep searches efficient.</p><h3>C. Parallel Search</h3><p>Elasticsearch is a <strong>multi-threaded</strong> giant. It doesn’t scan segments one by one; it uses multiple CPU cores to dive into many segments simultaneously.</p><h3>7. What Happens on Reboot? (Translog Recovery)</h3><p>When Elasticsearch starts up, it performs a check:</p><ol><li><strong>Disk Check:</strong> “When was my last Lucene Commit (Flush)?”</li><li><strong>Translog Analysis:</strong> It compares the disk segments with the Translog file. Since the Translog contains everything acknowledged but not yet flushed to disk, it holds the “missing” data.</li><li><strong>Recovery:</strong> Elasticsearch replays all operations in the Translog sequentially, bringing them back into memory. This is <strong>Translog Recovery</strong>, ensuring zero data loss.</li></ol><h3>Peeking Under the Hood: What’s Inside the Index Folder?</h3><p>For those who are curious about where these concepts actually “live” on the server, you can find them by navigating to your data path (usually /var/lib/elasticsearch/nodes/0/indices/.../0/index/).</p><ul><li>.tim / .tip: Inverted Index (The heart of search).</li><li>.si: Segment metadata.(you can think of this as Segment’s id card)</li><li>.dim: Dimensional points (for numeric/geo data).</li><li>_0.cfe / _0.cfs: The Compound File where the actual data lives.</li></ul><h3><strong>Summary: The Balance of Speed and Safety</strong></h3><p>By using <strong>RAM</strong> for near real-time speed (Refresh) and a <strong>Translog</strong> for immediate safety, it ensures that your data is always protected and nearly always searchable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833e7843ea7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Volatile Nedir? CPU Cache, Store Buffer ve Memory Ordering ile Gerçek Anlamı]]></title>
            <link>https://medium.com/@erhan355/volatile-nedir-cpu-cache-store-buffer-ve-memory-ordering-ile-ger%C3%A7ek-anlam%C4%B1-289aeb65a3fb?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/289aeb65a3fb</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 21:42:42 GMT</pubDate>
            <atom:updated>2026-04-03T18:13:53.997Z</atom:updated>
            <content:encoded><![CDATA[<p>Ön bilgi : <br>Bir thread’in bellek erişimi doğrudan RAM üzerinden gerçekleşmez. Modern CPU’larda bellek hiyerarşisi şu şekildedir:</p><p><strong>Okuma işlemi için tipik akış:</strong></p><pre>Register → L1 Cache → L2 Cache → L3 Cache → RAM</pre><p><strong>Yazma işlemi için tipik akış:</strong></p><p>CPU önce veriyi Store Buffer’a (yazma tamponu) koyar. Bu sayede işlem çok hızlı biter ve CPU diğer işlerine devam edebilir. Store Buffer’daki veriler daha sonra asenkron olarak L1 Cache’e (ve gerekirse alt seviyelere) yazılır.</p><pre>Register<br>   ↓<br>L1 Data Cache ←  Store Buffer (yazma işlemleri burada tamponlanır)<br>   ↓<br>L2 Cache<br>   ↓<br>L3 Cache (tüm core’lar arasında paylaşılan)<br>   ↓<br>RAM</pre><p><strong>Cache Coherence Protokolü Ne Yapar?</strong></p><p>Modern çok çekirdekli CPU’larda her core’un kendi L1 ve L2 cache’i vardır.</p><p>Bir core (örneğin CPU1) bir bellek adresindeki veriyi <strong>değiştirdiğinde</strong> (yazdığında), diğer core’ların cache’lerinde tutulan eski kopyalar sorun yaratabilir.</p><p>Bu sorunu çözmek için <strong>Cache Coherence Protokolü</strong> devreye girer. En yaygın kullanılanı <strong>MESI protokolü</strong>dür (ve türevleri).</p><p><strong>MESI protokolü basitçe şöyle çalışır:</strong></p><p>Bir core (CPU1) bir veriyi değiştirmek istediğinde:</p><ul><li>Diğer core’larda aynı veri varsa, onlara <strong>“bu veriyi geçersiz kıl”</strong> mesajı gönderilir (invalidate).</li><li>Diğer core’lar kendi cache’lerindeki o satırı <strong>Invalid</strong> (geçersiz) durumuna getirir. Yani eski kopya silinir.</li><li>CPU1 ise o veriyi <strong>Modified</strong> (değiştirilmiş) durumuna alır ve değişikliği yapar.</li></ul><p><strong>Sonuç olarak:</strong></p><ul><li>Diğer core’lar artık o cache satırındaki <strong>eski değeri</strong> kullanamaz.</li><li>Bir dahaki sefer o veriyi okumak istediklerinde cache miss olur ve <strong>güncel değeri</strong> cache hiyerarşisinden (L3 veya RAM’den) almak zorunda kalır.</li></ul><p>Bu mekanizma sayesinde tüm core’lar aynı bellek adresi için <strong>tutarlı</strong> (coherent) bir görüşe sahip olur. Yani bir core veriyi değiştirdiğinde, diğer core’lar eski versiyonu görmez.</p><p><strong>Thread Bir Değişkene Yazdığında Ne Olur?</strong></p><p>Bir thread bir değişkene değer yazdığında şu adımlar gerçekleşir:</p><ol><li>Değer önce CPU register’larında hesaplanır.</li><li>Yazma işlemi <strong>Store Buffer</strong>’a alınır (CPU bu sayede çok hızlı devam eder).</li><li>Store Buffer’daki veriler daha sonra asenkron olarak L1 Cache’e aktarılır.</li><li>Gerektiğinde L2 → L3 → RAM yoluna devam eder.</li></ol><p>Veri henüz Store Buffer’dayken diğer çekirdekler bu değişikliği göremez.Çünkü Store Buffer, o core’a özel bir tampon bölgedir.</p><p>MESI protokolü ancak veri L1 Cache’e ulaştığında devreye girer ve diğer core’lardaki eski kopyaları geçersiz kılar.</p><p><strong>Thread Bir Değişkeni Nasıl Okur ?</strong></p><p>Okuma sırası:</p><ol><li>Register</li><li>L1 Cache</li><li>L2 Cache</li><li>L3 Cache</li><li>RAM</li></ol><p>İlk bulduğu yerden okur.</p><p>CPU okuma yaparken diğer çekirdeklere “biri yazdı mı?” diye sormaz.<br>Cache satırı geçerliyse doğrudan onu kullanır.</p><p><strong>CPU Neden Store Buffer Kullanır?</strong></p><p>Çünkü:</p><p>CPU’nun bellek gecikmesini beklemeden çalışmaya devam etmesini sağlar<br>Performansı ciddi şekilde artırır.</p><p>Ama bunun bedeli vardır:</p><p>❗ Diğer çekirdekler yazılan değeri <strong>hemen göremeyebilir.</strong></p><p><strong>Volatile Ne Yapar?</strong></p><p><strong>🔹 Volatile WRITE</strong></p><pre>volatileFlag = true;</pre><p>Volatile write, önceki write’ların diğer core’lar tarafından görülebileceğini garanti eder (genellikle store buffer flush veya eşdeğer mekanizmalarla).</p><p>Örnek de Store Buffer Flush ile anlatım yapılmaktadır.(Gerçek işleyiş Architecture’a göre değişebilir)</p><p><strong>🔹 Adım 1: Store Buffer Flush</strong></p><p>“Benden önceki tüm yazılar artık görünür olmalı”</p><p>Yani:</p><ul><li>Store buffer’daki yazmaların görünür olması garanti edilir<br>(genellikle flush veya eşdeğer mekanizmalar ile)</li></ul><p><strong>🔹 Adım 2: Cache Coherence</strong></p><ul><li>Diğer çekirdeklere haber gider</li><li>Gerekirse diğer çekirdeklerdeki cache line’lar invalidate edilir</li><li>Veya güncellenir (MESI’ye göre)</li></ul><p><strong>🔹 Adım 3: Volatile değer yazılır</strong></p><p>Sonuç:</p><p>Bir çekirdek volatile değeri güncel haliyle gözlemlerse,<br>ondan önceki tüm write’ları da güncel haliyle görür.</p><p><strong>Güncel değerini görememesi nasıl olabilir ?</strong></p><p><strong>Thread A (Core 1)</strong></p><pre>x = 1;<br>flag = true; // volatile</pre><p><strong>Thread B (Core 2)</strong></p><pre>if (flag)<br>    print(x);</pre><p>Core1:</p><ul><li>x = 1 → store buffer / cache</li><li>flag = true → yazıldı</li></ul><p>Ama:<br>Bu bilgi henüz Core2’ye ulaşmamış olabilir</p><pre>if (flag)</pre><p>hala <strong>eski cache line</strong>’ı kullanıyor olabilir:(flag = false)</p><p><strong>Peki volatile neyi garanti ediyor?</strong></p><p>Eğer Core2 şunu görürse</p><pre>flag = true</pre><p>O zaman:</p><pre>x = 1 görmek zorunda</pre><p>Yani özetle ;</p><p>Volatile, diğer çekirdeklerin eski değeri asla okuyamayacağını garanti etmez.<br>Ancak bir çekirdek yeni değeri gözlemlediği anda,<br>önceki tüm write’ları da doğru ve tutarlı şekilde görmek zorundadır.</p><p>Read kısmına geçmeden önce ;</p><p><strong>Speculative Read (Tahminli Okuma)<br></strong>Örnek:</p><pre>if (flag)<br>    Use(data);</pre><p>CPU performans için şunu yapabilir:</p><ul><li>flag henüz kontrol edilmeden</li><li>data okunur (tahmini okuma)</li><li>Eğer flag == false çıkarsa sonuç çöpe atılır</li></ul><p>Bu tamamen <strong>zaman kazanma amacıyla yapılan bir tahmindir</strong>.</p><p><strong>Volatile ile İlişkisi</strong></p><p>Örnek:</p><pre>int data = 0;<br>bool flag = false; // volatile DEĞİL<br><br>void Writer() {<br>    data = 42;<br>    flag = true;<br>}<br><br>void Reader() {<br>    if (flag) {<br>        Console.WriteLine(data);<br>    }<br>}</pre><p><strong>Sorun:</strong></p><ul><li>CPU, <strong>instruction reordering</strong> yapabilir.</li></ul><pre>flag = true;<br>data = 42;</pre><p>Bunun sebebi:</p><ul><li>data ile flag arasında <strong>doğrudan bir bağımlılık yoktur</strong></li><li>CPU için bu iki yazımın sırası “önemsiz” görünür</li><li>Ama bizim mantığımız için ÖNEMLİDİR.</li></ul><p><strong>Olası Senaryo</strong></p><p><strong>Çekirdek 1 (Writer)</strong></p><pre>flag = true   ← önce çalıştı<br>data = 42     ← sonra çalıştı</pre><p><strong>Çekirdek 2 (Reader)</strong></p><pre>flag == true  <br>data == 0     </pre><p>Sonuç:</p><ul><li>Reader, flag’i <strong>true</strong> görür</li><li>Ama data hâlâ eski değerdedir</li><li>Program mantıksal olarak bozulur</li></ul><p><strong>Bu Neden Olur?</strong></p><p>Çünkü:</p><p>CPU instruction reordering yapabilir<br>Store buffer yazmaları geciktirebilir<br>Cache henüz senkronize olmamış olabilir<br>Diğer çekirdek eski cache satırını kullanıyor olabilir</p><p>Ve <strong>hiçbiri mimariye aykırı değildir.</strong></p><p><strong>Volatile Ne Sağlar?<br>Yazma Bariyeri (Store Barrier)</strong></p><pre>data = 42;<br>flag = true; // volatile</pre><p>CPU şunu yapmak ZORUNDA:</p><ul><li>data = 42 bitmeden flag = true yazamaz</li></ul><p>Yani data yazılmadan flag yazılamaz</p><p><strong>Okuma Bariyeri (Load Barrier)</strong></p><pre>if (flag) {<br>    Console.WriteLine(data);<br>}</pre><p>CPU şunu yapamaz:</p><ul><li>Datayı flag’den önce tahmini olarak okuyamaz</li><li>Eski cache değerini kullanamaz</li></ul><p>Önce: flag → güncel mi?<br>Sonra: data → oku</p><p><strong>Volatile Read Ne Yapar?</strong></p><pre>if (volatileFlag)</pre><p>Bir volatile değişken okunduğunda, bu okumadan sonra yapılan işlemler,<br>bu okumadan önceki write’lardan önce gerçekleşemez.</p><p>Yani:<br>Bir thread volatile değeri gördüğünde, o değere kadar yapılan tüm write’ları da doğru sırada görür.</p><p>CPU şu garantileri verir:</p><p>Önceki speculative read’ler iptal edilir.<br>Değer cache’ten <strong>güncel hâliyle</strong> okunur.<br>Bu satırdan sonraki işlemler öne çekilemez.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289aeb65a3fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read-Only ≠ Immutable in .NET]]></title>
            <link>https://medium.com/@erhan355/read-only-immutable-in-net-4fa4b55761a3?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa4b55761a3</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 19:48:41 GMT</pubDate>
            <atom:updated>2026-01-14T19:48:41.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>Read-Only ≠ Immutable in .NET</h3><p>I see that many times, lots of developers(including me) can be confused about this concept.</p><p><strong>What “Read-Only” Actually Means<br></strong> <br> The most accurate definition that comes to mind about this is the following.</p><p><strong>Read-only means: “You cannot mutate this object through this reference.”</strong></p><p>A <strong>Read-only</strong> collection is a “view” or a “window” into another collection; hence If the original list is modified, the read-only view changes too</p><p>IReadOnlyList&lt;T&gt;: A Restricted View</p><p><strong>What it allows</strong></p><pre>var first = list[0];<br>var count = list.Count;<br><br>foreach (var item in list)<br>{<br>    Console.WriteLine(item);<br>}</pre><p><strong>What it forbids</strong></p><pre><br>list.Add(&quot;x&quot;);     <br>list.Remove(&quot;x&quot;);  <br>list[0] = &quot;y&quot;;  </pre><p><strong>Read-Only Does NOT Mean Immutable</strong></p><p><strong>Example: underlying data can still change</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*eOl_Xp9oApOVoGPWfGnrJw.png" /></figure><p>Same Story for IReadOnlySet too</p><p><strong>Immutable Collections<br></strong>An “Immutable” collection is like a <strong>photograph.(In fact snapshot)</strong></p><p>Once it is created, it can <strong>never</strong> change.</p><p>If you try to “mutate” it (e.g., by calling .Add()), it doesn&#39;t change the original object; instead, it returns a <strong>completely new</strong> object with the change applied.</p><ul><li>ImmutableArray&lt;T&gt;</li><li>ImmutableList&lt;T&gt;</li><li>ImmutableHashSet&lt;T&gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*M_2Fk9b21RLLmNURDd9XAQ.png" /></figure><p><strong><em>Another confusion</em></strong></p><p>It was immutable; we managed to mutate it? <br>It outputs 29 for the both original and immutable collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*33GQDWIB3NLGL_VVX81Z8Q.png" /></figure><p>In fact No !</p><p>The <strong>ImmutableArray</strong> is doing its job perfectly: it is protecting the <strong>list of references</strong>. However, it does not automatically protect the <strong>objects inside</strong> those references</p><p>When you create an ImmutableArray&lt;User&gt;, you are creating an unchangeable set of &quot;pointers&quot; to memory addresses.</p><ol><li><strong>The Array is Immutable:</strong> You cannot add a new user, remove a user, or swap out index [0] for a different User object. If you tried immutableNames[0] = new User(&quot;Erhan&quot;), the compiler would stop you with an error.</li><li><strong>The Object is Mutable:</strong> The object sitting at that memory address (the User class) is still a regular, mutable class. When you write immutableNames[0].Name = &quot;Erhan&quot;, you aren&#39;t changing the array; you are following the pointer to the object and changing a value <strong>inside</strong> that object.</li></ol><p>I hope it is clearer now. ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa4b55761a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Immutable Structs and Ref Structs in C#]]></title>
            <link>https://medium.com/@erhan355/the-power-of-immutable-structs-and-ref-structs-in-c-91cfe92b3a72?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/91cfe92b3a72</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 14:19:58 GMT</pubDate>
            <atom:updated>2026-01-09T14:19:58.592Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>struct</strong> in C# is a <strong>value type</strong> that holds data directly in memory (typically on the stack), unlike reference types like classes, which store references to objects.</p><p>As said before, structs are value types and, as such, don’t support inheritance. However, they can implement interfaces.</p><p>This makes structs <strong>lightweight</strong> and <strong>fast</strong>, but they’re typically used for small, simple data structures, such as Point, Vector, or DateTime.</p><p><strong>Confusion with Reference Types Inside Structs</strong></p><p>A key source of confusion arises when a struct contains <strong>reference type fields</strong> (e.g., a class or string). Structs copy <strong>references</strong>, not the objects themselves. So, if you assign one struct to another, you <strong>share the same reference</strong> for reference type fields.</p><pre>using System;<br><br>public class MyClass<br>{<br>    public string Value;<br><br>    public MyClass(string value)<br>    {<br>        Value = value;<br>    }<br>}<br><br>public struct MyStruct<br>{<br>    public MyClass myClass; // Reference type field (class)<br><br>    public MyStruct(MyClass myClass)<br>    {<br>        this.myClass = myClass;<br>    }<br>}<br><br>public class Program<br>{<br>    public static void Main()<br>    {<br>        // Create a MyClass object<br>        MyClass class1 = new MyClass(&quot;Hello&quot;);<br><br>        // Create a struct containing the reference type field<br>        MyStruct struct1 = new MyStruct(class1);<br><br>        // Assign struct1 to struct2 (this copies the struct, but shares the reference to class1)<br>        MyStruct struct2 = struct1;<br><br>        // Modify the Value property of the class instance through struct2<br>        struct2.myClass.Value = &quot;World&quot;;<br><br>        // Print both structs and the referenced object&#39;s Value<br>        Console.WriteLine($&quot;struct1.myClass.Value: {struct1.myClass.Value}&quot;); // Output: World<br>        Console.WriteLine($&quot;struct2.myClass.Value: {struct2.myClass.Value}&quot;); // Output: World<br>    }<br>}</pre><p><strong>Read-only Structs</strong></p><ul><li><strong>Prevents accidental mutation</strong>: No setters or reassignments after initialization.</li><li><strong>Optimized</strong>: The compiler can optimize <strong>immutable structs</strong> for performance.</li><li><strong>Thread-safe</strong>: <strong>Immutable structs</strong> are naturally thread-safe.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NdufyASTWqVXMX33Zg3CRA.png" /></figure><p><strong>Ref Struct</strong></p><p>A ref struct is a special kind of struct introduced to manage stack-allocated memory and avoid heap allocation. ref struct has strict limitations, such as:<strong><br> <br>It must stay on the stack</strong>: It can never be boxed or moved to the heap.(see below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*TIUffDjoE4GCsTcrc1ljTQ.png" /></figure><p>However, the <strong>data</strong> inside the struct can point to the heap. When you include a string property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*f-NwQccQV0qv5V7We9TW9w.png" /></figure><p>The <strong>reference</strong> (the pointer to the string) stays on the stack within the struct.</p><p>The <strong>string object</strong> itself remains on the managed heap as usual.</p><p>Note: Because the compiler converts an async method into a <strong>state machine that is converted to a class and stored on the heap</strong>, and a ref struct can only <strong>exist on the stack</strong>, it cannot be used in async methods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*g8DtzYMd_oWdbVP4S3M-hg.png" /></figure><p><strong>In C# 13 and later:</strong></p><ul><li><strong>ref struct and async methods</strong> can work together, but with some conditions:</li></ul><p>If a <strong>ref struct</strong> is used in an <strong>async</strong> method <strong>before any await</strong> is used, the ref struct stays on the stack, and no issues arise. The compiler allows this without errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KDOgRAR2u2I38YkgizdebA.png" /></figure><p><strong>Why It Works Before await</strong></p><p>When you define a ref struct before any await call, the method is still executing in a linear flow, not in a split state machine.</p><p>Also ; <br><strong>In C# 13 and later:</strong><br>A ref struct can implement interfaces, but must adhere to the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/structs#1623-ref-modifier">ref safety</a> rules.This works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*vgCUkGl-gSLYHltSNV8tkQ.png" /></figure><p>But this doesn&#39;t work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*EyBYTkmxkutHNLSjzVeKMg.png" /></figure><p><strong>Why ?</strong></p><p>When you attempt to assign a ref struct to an interface (IMyInterface in this case), the runtime requires a “boxing” operation to store the ref struct in a reference type (the IMyInterface). However, ref structs cannot be boxed because they are stack-only types.</p><p><strong>Common ref struct Types in .NET</strong></p><p>You likely use these daily without realizing the power under the hood:</p><ul><li>Span&lt;T&gt;: Points to contiguous memory (array, string, or stack) without copying.</li><li>ReadOnlySpan&lt;T&gt;: The immutable version of Span, perfect for parsing.</li><li>Utf8JsonReader: A high-performance, forward-only JSON tokenizer that doesn’t allocate strings for keys or values.</li><li>ValueStringBuilder: A stack-based alternative to StringBuilder used internally by .NET to stitch strings together with zero heap overhead.</li></ul><p><strong>Why do we use them?</strong></p><p><strong>1. Zero Garbage Collection (GC) Pressure</strong></p><p>In a standard application, creating objects (like new byte[] or new string) puts them on the <strong>Heap</strong>. The GC must eventually scan the heap, identify unused objects, and delete them. This “stop-the-world” process slows down your app.</p><ul><li><strong>The ref struct Advantage:</strong> Because it is <strong>stack-only</strong>, it is automatically discarded the moment the method ends.</li><li><strong>The Result:</strong> The GC never sees it, never tracks it, and never has to clean it up. It is “free” memory management.</li></ul><p><strong>2. Safe “Managed Pointers” (Interior Pointers)</strong></p><p>A standard reference (like a string variable) can only point to the <strong>start</strong> of an object. A ref struct can hold a <strong>Managed Pointer</strong> (ref T) that points <strong>anywhere</strong>.</p><ul><li><strong>Automatic Updates:</strong> If the GC moves the original object (like your string) to a new location on the heap to defragment memory, it automatically finds your ref struct on the stack and <strong>updates the address</strong> it is holding.</li><li><strong>Safety Guards:</strong> The compiler prevents you from saving these pointers into a class. This ensures you never have a pointer pointing to a “dead” memory location.</li></ul><p><strong>3. Working with stackalloc</strong></p><p>stackalloc is the fastest way to get a block of memory because it carves it out of the CPU’s current stack frame.</p><ul><li><strong>The Problem:</strong> Raw stack memory is dangerous. If you passed a raw pointer to stack memory around, you could easily crash the program.</li><li><strong>The Solution:</strong> Span&lt;T&gt; (a ref struct) wraps that stack memory. It gives you array-like access but uses the ref struct rules to make sure that memory <strong>never leaves the stack frame</strong> where it was created.</li></ul><p><strong>Examples</strong></p><p><strong>Substring() vs AsSpan().Slice()</strong></p><p>Imagine you have a string “Hello World” at memory address <strong>0x100</strong>. You want the word “World”.</p><p><strong>Traditional: string.Substring(6)</strong></p><ol><li>A <strong>new object</strong> is created on the Heap (Address <strong>0x200</strong>).</li><li>The characters ‘W’,’o’,’r’,’l’,’d’ are <strong>copied</strong> from the old memory to the new memory.</li><li>You now have two separate objects for the GC to track.</li></ol><p><strong>High Performance: ReadOnlySpan&lt;char&gt;.Slice(6)</strong></p><ol><li><strong>No new object</strong> is created on the heap.</li><li>A small ref struct is created on the <strong>Stack</strong>.</li><li>It simply stores: <strong>Start Address: 0x106</strong> and <strong>Length: 5</strong>.</li></ol><p><strong>Utf8JsonReader</strong></p><pre>// 1. Assignment: The reader is a &#39;ref struct&#39; on the stack. <br>// It stores the START ADDRESS and SIZE of your huge log.<br>var reader = new Utf8JsonReader(jsonUtf8Bytes, options);<br><br>// 2. The Move: This doesn&#39;t &quot;load&quot; data. <br>// It just moves the pointer to the next token.<br>while (reader.Read())  {<br>    // The reader.Read() call does NOT fetch or load new data. <br>    // It simply moves the &#39;internal pointer&#39; forward to the next token in the buffer.<br><br>    if (reader.TokenType == JsonTokenType.PropertyName)<br>    {<br>// 3. The Slice: &#39;ValueSpan&#39; is a tiny window (pointer + length). <br>// It points to the bytes ALREADY in your log.<br>        ReadOnlySpan&lt;byte&gt; name = reader.ValueSpan; <br><br>// 4. Comparison: We compare raw bytes without creating a string!<br>        if (name.SequenceEqual(&quot;id&quot;u8)) <br>        {<br>// Found it with ZERO heap allocations.        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91cfe92b3a72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async Isn’t Magic]]></title>
            <link>https://medium.com/@erhan355/async-isnt-magic-7d8314e8d9b0?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d8314e8d9b0</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 13:52:24 GMT</pubDate>
            <atom:updated>2025-12-21T13:52:24.984Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s basically state machines, logical flows, and a little AsyncLocal.</p><p><strong>The One Rule: A Real Async Method Exists Only If…</strong></p><p>An async state machine is generated <strong>only when two things are true:<br></strong>1. The method is marked async</p><pre>public async Task DoSomething() { }</pre><p>2. It contains at least one await that may yield</p><pre>public async Task DoSomething()<br>{<br>    Console.WriteLine(&quot;A&quot;);<br>    await Task.Delay(500); // may yield → compiler creates a state machine<br>    Console.WriteLine(&quot;B&quot;);<br>}</pre><p>When the compiler sees that await,it rewrites your code:</p><ul><li>It splits the method into parts</li><li>It stores local variables</li><li>It remembers “where to resume.”</li><li>It schedules a continuation</li><li>It returns control to the caller</li></ul><p>In other words, async is just a fancy code-splitter.</p><p>What if an async method has <em>no await</em>?</p><pre>public async Task Foo()<br>{<br>    Console.WriteLine(&quot;Hello&quot;);<br>}</pre><p>This compiles:</p><pre>public async Task Foo()<br>{<br>    Console.WriteLine(&quot;Hello&quot;);<br>}</pre><p>But the compiler warns you:</p><blockquote>“This async method lacks ‘await’ operators and will run synchronously.”<br>No state machine is created.<br> The method runs synchronously and returns Task.CompletedTask.</blockquote><p><strong>AsyncLocal in the real world</strong></p><p>Enough theory.Let’s talk practical value.</p><p>I recently built a background job system on top of <strong>Hangfire</strong> for a scraping service.<br>Each scraping job can choose its own <strong>maximum parallel product processing</strong> — basically how many products we allow to be scraped in parallel.</p><p>The easy approach would be:</p><ul><li>Pass this setting down through every layer</li><li>Thread it through dozens of method calls</li><li>Let the entire method chain explode with new parameters</li></ul><p>But that’s miserable.</p><p>Instead, .NET gives us a neat solution: <strong>AsyncLocal&lt;T&gt;</strong>.</p><p>AsyncLocal — ambient data per logical async flow</p><p>Here’s a tiny version of what I did:</p><pre>public static class ScraperRunContext<br>{<br>    private static readonly AsyncLocal&lt;int?&gt; _maxParallelOverride = new();<br><br>    public static int? MaxParallelOverride<br>    {<br>        get =&gt; _maxParallelOverride.Value;<br>        set =&gt; _maxParallelOverride.Value = value;<br>    }<br>}</pre><p>Even though _maxParallelOverride is a <em>static</em> field, each async execution flow gets its <strong>own value</strong>.</p><p>That means:</p><ul><li>Multiple Hangfire jobs may run concurrently</li><li>Each job can set its own parallel limit</li><li>Deep internal code (that never heard about job parameters) can read it</li></ul><p>All because the <strong>ExecutionContext flows across awaits.</strong></p><p><strong>Using it inside a Hangfire job handler<br></strong>Inside each job:</p><pre>ScraperRunContext.MaxParallelOverride = parameters.MaxParallelProductProcessing;<br><br>var result = await _scraperService.SearchAndExtractBrandsAsync(<br>    parameters,<br>    cancellationToken,<br>    async (current, total, brandsFound) =&gt;<br>    {<br>        await _jobStatusService.UpdateJobProgressAsync(jobId, current, total, brandsFound);<br>    });</pre><p>Later, no matter <em>how deep</em> we are in the scraping pipeline, we can write:</p><p><strong>Why?</strong></p><p>Because the compiler already generated a state machine for this entire async workflow.<br>Every await preserves the ExecutionContext.<br> AsyncLocal values ride along inside that context.</p><p><strong>Concurrent jobs → separate logical values</strong></p><p>A normal static field would get clobbered:</p><ul><li>Job A sets the value to 5</li><li>Job B sets the value to 12</li><li>Suddenly, both see 12</li></ul><p>But AsyncLocal doesn’t behave like a global mutable integer.</p><p>Because each async state machine has its own ExecutionContext snapshot, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*q_6FluiqR240xvVc2N0_8g.png" /></figure><p>That’s perfect, “ambient per job configuration.”</p><p><strong>Clearing values is important</strong></p><p>I finished each job with:</p><pre>finally<br>{<br>    ScraperRunContext.MaxParallelOverride = null;<br>}</pre><p>If you forget that:</p><ul><li>A later continuation could inherit stale values</li><li>Fire-and-forget tasks may run with old settings</li></ul><p>Cleaning up is part of the contract.</p><p><strong>A great mental model</strong></p><p>Here’s how everything ties together:</p><p>Async state machines preserve ExecutionContext.<br>ExecutionContext carries AsyncLocal values.<strong><br></strong> Therefore, every async workflow can have its own ambient state.</p><p>Combine that with Hangfire and you get:</p><blockquote><em>“One static field, many independent logical values.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d8314e8d9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BlockingCollection vs. Channels in C#: What’s the Difference?]]></title>
            <link>https://medium.com/@erhan355/blockingcollection-vs-channels-in-c-whats-the-difference-8b742fc332f4?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b742fc332f4</guid>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 20:41:52 GMT</pubDate>
            <atom:updated>2025-11-20T20:41:52.984Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>BlockingCollection</strong> and <strong>Channels</strong> solve similar problems but work in very different ways.</p><p><strong>BlockingCollection: The Classic Approach</strong></p><p>BlockingCollection is built around the producer–consumer pattern. It wraps a thread-safe collection—ConcurrentQueue by default, but it can also use ConcurrentStack or ConcurrentBag</p><p>You can define a <strong>bounded capacity</strong>, which means the collection can only hold a fixed number of items. When the producer tries to add an item and the collection is full, the call <em>blocks</em> until a consumer removes something.</p><p>Likewise, if the consumer tries to take an item when the collection is empty, it waits until a new item arrives. This all happens automatically — no manual locking or signaling.</p><p>It’s a simple and safe way to coordinate producers and consumers in synchronous code.</p><p><strong>Channels: The Modern Async Pipeline</strong></p><p>The idea is the same, but with one big difference : <br>Channels are designed for <strong>async, non-blocking scenarios</strong>.</p><p>Instead of blocking threads, Channels use await:</p><pre>await channel.Writer.WriteAsync(item);<br>var item = await channel.Reader.ReadAsync();</pre><p>This means no thread sits idle while waiting. It scales much better in applications that are already async — like servers, I/O pipelines, or background processing.</p><p>You can choose unbounded channels, bounded channels, or optimized configurations like single-writer or single-reader to get even better performance.</p><h3>How they differ</h3><p>Here’s the difference in simple terms:</p><p><em>BlockingCollection is synchronous and blocking.</em>Channels are asynchronous and non-blocking.</p><p>BlockingCollection blocks threads; Channels release them.</p><p>BlockingCollection is older TPL-based technology; Channels are the modern replacement.</p><p>await channel.Writer.WriteAsync(item);<br>var item = await channel.Reader.ReadAsync();</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b742fc332f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservisler ve Two-Three Phase Commit]]></title>
            <link>https://medium.com/@erhan355/microservisler-ve-two-three-phase-commit-53b781297315?source=rss-27904bb845f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b781297315</guid>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[three-phase-commit]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[two-phase-commit]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[erhan355]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 18:22:59 GMT</pubDate>
            <atom:updated>2025-10-21T18:22:59.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL’de Isolation (Yalıtım) Seviyeleri — Ön Bilgi</h3><p><strong>Varsayılan:</strong> READ COMMITTED</p><p>Veritabanı işlemlerinde aynı anda birden fazla işlem yürütüldüğünde tutarsızlıklar oluşabilir. Bu durumları anlamak için temel izolasyon seviyelerine bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*JEAD0zHnR4f7F6PUWaBTNA.png" /></figure><h3>🔸 Non-Repeatable Read</h3><p>Bir işlem aynı satırı iki kez okur, fakat arada başka bir işlem bu veriyi güncellerse sonuçlar farklılaşır.</p><p><strong>Örnek:</strong><br> Transaction A bakiyeyi okur: 500 TL<br> Transaction B bu bakiyeyi 300 TL’ye düşürür.<br> Transaction A tekrar okuduğunda 300 TL görür.</p><h3>🔸 Phantom Read</h3><p>İşlem sırasında yeni kayıtlar eklenir veya silinirse okuma sonuçları değişir.</p><p><strong>Örnek:</strong><br> Transaction A 3 satır okur.<br> Transaction B yeni bir satır ekler.<br> Transaction A tekrar okuduğunda 4 satır görür.</p><h3>🔸 Dirty Read</h3><p>Bir işlem, diğerinin <strong>commit etmeden önce</strong> oluşturduğu veriyi okur.</p><p><strong>Örnek:</strong><br> Transaction B bir değişiklik yapar ancak commit etmeden rollback yapar.<br> Transaction A rollback öncesi değeri okuduğu için “dirty data” okur.</p><h3>SQL Server’da Lock (Kilit) Davranışı</h3><blockquote>READ COMMITTED seviyesinde, bir satır güncellenirken başka bir işlem o satırı okumak isterse bekler.</blockquote><blockquote>Örnek <br>Transaction A, ID’si 3 olan bir veriyi güncelliyor. Biz SELECT * sorgusunu çalıştırırsak, Transaction A’nın işlemi bitene kadar bekleriz</blockquote><blockquote>NOLOCK kullanıldığında bekleme olmaz ama “dirty read” riski artar.</blockquote><blockquote>Satırların hepsini çekmek istemiyorsak doğrudan belirli id li satırı çekersek (örnek id 4 olsun) bu durumda beklememize gerek kalmaz çünkü sql tabloya row lock atmıştır.Tabi ki bu her zaman doğru değildir.</blockquote><p>Bir işlem id si 3 olan kaydı güncelliyorsa ve başka bir işlem id si 2 olan kaydı okumak için bir sorgu atıyorsa ve her iki kayıt da aynı page de ise , SQL Server page düzeyinde bir kilit alabilir.</p><p>Özetle ; <br>SQL Server bazen <strong>row lock</strong> yerine <strong>page lock</strong> alabilir. Bu tablo boyutu ve sorgu yapısına bağlıdır.</p><h3>ACID Prensipleri</h3><p>Veritabanı işlemlerinde güvenilirliği sağlayan dört temel ilke vardır:</p><ol><li><strong>Atomicity (Atomiklik):</strong></li></ol><p>İşlem ya tamamen gerçekleşir ya da hiç gerçekleşmez.</p><blockquote>Örneğin User A nın hesabından B ye para aktarırken transaction başlatıyorsak A nın hesabından para çekilip B ye yatar ya da ilk haline geri döner.A nın hesabın dan eksilip B ye yatmama gibi durum olmaz.</blockquote><blockquote><strong>2. Consistency (Tutarlılık):</strong></blockquote><blockquote>İşlemler, veritabanı kurallarını ihlal etmeden tamamlanmalıdır.</blockquote><blockquote>Transaction database constraint lere uymak zorundadır.Mesela yukarıdaki örnekte para transferi yapılırken transfer edilecek para negatif değer olamaz.(Db de amountToTransfer column un her zaman pozitif olması constraint i olduğunu varsayıyorum.)</blockquote><p><strong>3. Isolation (Yalıtım):</strong><br> İşlemler birbirinden bağımsız yürütülür. Aynı anda aynı kaydı değiştirmeye çalışan işlemler sıraya alınır.</p><blockquote>Örneğin Transaction A ve B aynı anda kullanıcı hesabından para çekmeye çalışamaz,biri diğerini beklemek zorundadır.</blockquote><blockquote><strong>4. Durability (Kalıcılık):</strong><br> Commit edilmiş bir işlem sistem çökse bile kaybolmaz.</blockquote><h3>Microservisler ve ACID Prensipleri</h3><p>Monolitik sistemlerde örneğin bir sipariş işlendiğinde:<br> Transaction başlar → Customer tablosu güncellenir → Order tablosu güncellenir → Commit edilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*ETmNQpTYBn93oxLe-psUOA.png" /></figure><p>Microservice mimarisi distributed (dağıtık) yapıya sahip olduğundan ACID prensiplerini yönetmek monolitik yapılara göre daha zordur. Microservisler de farklı yaklaşımlar kullanmalıyız.</p><p>Örneğin : 2 phase commit yapmalıyız.(Foto 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*eJ4hk_kVT0o5KWMI58j_4g.png" /></figure><p><strong>Two-Phase Commit (2PC) Mantığı<br></strong>Sistemde bir <strong>coordinator (koordinatör)</strong> servis bulunur. Bu servis işlemin bütünlüğünü yönetir.</p><ol><li><strong>Hazırlık (Prepare) Aşaması:</strong><br> Öncelikle kendisine subscribe (abone) olmuş tüm servislere işlemi gerçekleştirmeye hazır olup olmadıklarıyla ilgili commit gönderir. Eğer servislere erişilemez ya da hata ile karşılaşılırsa akış iptal edilir.</li><li><strong>Commit Aşaması:</strong><br> Tüm servisler “hazırım” dediyse, koordinatör komutları gönderir.<br>Örneğin : Customer servisi bakiyeyi günceller, Order servisi siparişi oluşturur.</li><li><strong>Tamamlama:</strong><br> Tüm servisler başarılı dönerse koordinatör commit yapar.<br> Biri başarısız olursa rollback çağrıları gönderilir.</li></ol><p>2PC Başarılı Senaryo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*KTs2ksnNd9rTetFay9zV0A.png" /></figure><p>2PC Başarısız Senaryo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*AW6xyv_zO4wK52VUyT-h6Q.png" /></figure><p>Buradaki problemlerden biri de her servisler için undo operation larıda yazmak zorunda olmamızdır. <br>Örneğin ; <br>Customer servisinde hata aldı, işlem gerçekleşmedi. Order Servisi commit ledi bu durumda undo komutu/call ı göndermeliyiz.</p><p>Doğal olarak undo yaparken de sorunlar yaşabiliriz, örneğin Customer servisi çökmüş olabilir.Bu durumda inventory den düşmemiş bir order ile karşı karşıya kalmış olduk. Servis tekrar ayağa kalktığında undo işlemini yapabiliriz.</p><p>Bu tarz sistemler eventually consistent sistemlerdir.</p><p>Örneğin ; <br>Yukarıdaki sisteme shipmentMicroServisi de ekleyelim.Customer,Order işini yaptı,fakat Shipment henüz işini bitirmedi ve shipment db sini güncelleyemedi.Tam o noktada db snapshot alıp baktığımızda inconsistent state de olduğunu görürüz.</p><p>Fakat shipmentMicroServisi de işini bitirdikten sonra bakarsak consistent olduğunu görürüz.Yani işin sonunda consistent olurlar.</p><p>Tabi ki başka sorunlarda var</p><p>Coordinator hazırlık aşamasını başlattıktan sonra başarısız olursa, nodlar arasından yeni koordinatör(recovery coordinator) seçilir, ancak yeni koordinator 1. aşamanın tüm mesajlarını toplamadan önce başka bir node daha çökerse, protokol devam edemez.</p><p>Diğer tüm katılımcı nodelar Ok dönmüş olsa bile, yeni çökmüş node abort etmeyi amaçlamış olabilir. Dolayısıyla recovery coordinator fail olan node ayağa kalkana kadar bekler.</p><p><strong>Three-Phase Commit (3PC)<br></strong>Three-Phase Commit, Two-Phase Commit’in geliştirilmiş halidir.</p><ul><li>Timeout fonksiyonları eklenmiştir.</li><li>Ek bir <strong>prepare-to-commit</strong> adımı vardır.</li><li>Katılımcı nodelar arası iletişim daha güvenlidir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dTsCaYJammVWpXYA_b5U4w.png" /></figure><p><strong>Not:</strong> Three-Phase Commit, Saga Pattern ile karıştırılmamalıdır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b781297315" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>