<?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 Sanskar agrawal on Medium]]></title>
        <description><![CDATA[Stories by Sanskar agrawal on Medium]]></description>
        <link>https://medium.com/@sanskaragr.14?source=rss-8edbc55dcdc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iRGSg_xJe42BEHEL</url>
            <title>Stories by Sanskar agrawal on Medium</title>
            <link>https://medium.com/@sanskaragr.14?source=rss-8edbc55dcdc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanskaragr.14/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[Race Conditions in Kafka Microservices: Handling Out-of-Order Events and Data Overwrites in…]]></title>
            <link>https://medium.com/@sanskaragr.14/race-conditions-in-kafka-microservices-handling-out-of-order-events-and-data-overwrites-in-cc2a61c44957?source=rss-8edbc55dcdc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2a61c44957</guid>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Sanskar agrawal]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 21:31:03 GMT</pubDate>
            <atom:updated>2025-08-11T14:51:07.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Race Conditions in Kafka Microservices: Handling Out-of-Order Events and Data Overwrites in Event-Driven Systems</h3><p>When multiple services process a single request in stages using Kafka, things can go wrong if you assume events will always arrive in order.</p><p>This post explores a realistic example — e-commerce order processing — and how to avoid data inconsistency, race conditions, and incorrect status updates in your system.</p><h4>The Real-World Problem: Tracking Multi-Stage Order Processing</h4><p>Let’s say we are building an e-commerce backend using Kafka and microservices. When a user places an order, it goes through <strong>several processing stages</strong>, handled by <strong>separate services</strong>.</p><p>Each service performs its part and publishes an event to a Kafka topic. This event is consumed by the next service or services (for simplicity in this post considering sequential execution) to complete the next stages in the process.</p><p>Events from all services are consumed by a <strong>query service</strong>, which updates the <strong>current status of the order</strong> in the DB. Query Service API will be used by UI(Order status page) to fetch the latest status of the user’s order.</p><p>Before going to the challenge lets first have a overview of the example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nli2anYHGAyTzURgyZpL2g.png" /></figure><h4>Service flow</h4><ol><li>UI (order booking page) → Order Service API (user submits order).</li><li>Order Service calls Inventory Service to reserve/decrement product count.</li><li>Order Service publishes order.received.</li><li>Query Service consumes order.received → creates DB entry with status orderInitiated.</li><li>User clicks Pay → UI calls Payment Service (sync); Payment Service responds to UI with pass/fail and also publishes to payment.status topic.</li><li>Inventory Service consumes payment.status: if failed → restore product count in items DB; if success → finalize reservation and publish inventory.checked.</li><li>Shipment Service consumes inventory.checked, initiates shipment and publishes shipment.status (and later updates as and when shipment status changes like OutForDelivery, Delivered e.t.c).</li><li>Query Service subscribes to all topics and updates the order row in DB accordingly (orderInitiated → paid/failed → inventoryChecked → shipped → delivered, …).</li></ol><pre>{<br>  &quot;orderId&quot;: &quot;ORD123&quot;,<br>  &quot;currentStatus&quot;: &quot;Shipped&quot;,<br>  &quot;history&quot;: [<br>    { &quot;stage&quot;: &quot;OrderInitiated&quot;, &quot;timestamp&quot;: &quot;12:01:33&quot; },<br>    { &quot;stage&quot;: &quot;PaymentCompleted&quot;, &quot;timestamp&quot;: &quot;12:01:41&quot; },<br>    { &quot;stage&quot;: &quot;Packed&quot;, &quot;timestamp&quot;: &quot;12:02:10&quot; },<br>    { &quot;stage&quot;: &quot;Shipped&quot;, &quot;timestamp&quot;: &quot;12:05:21&quot; }<br>  ]<br>}</pre><p><strong>Problem — race conditions &amp; out of order updates</strong></p><p><strong>Myth</strong>: Kafka ensures event ordering across all partitions, topics and consumers.</p><p><strong>Truth</strong>: Kafka <strong>guarantees ordering only within a partition</strong>. When 2 or more messages are published to a topic, and not to a specific partition, it is very much possible that a message which is published later gets consumed before the other. Similarly across topics.</p><p><strong>Scenario 1: out-of-order updates</strong></p><ul><li>Event from Order service (Stage: OrderInitiated) is published first.</li><li>Then, payment service processes and publishes event (Stage: PaymentCompleted).</li></ul><p>If:</p><ul><li>Query service receives PaymentCompleted first and updates status to PaymentCompleted.</li><li>Then the same instance slightly later processes OrderInitiated message and overwrites status.</li></ul><p>Result?</p><p>User sees outdated status OrderInitiated, despite the payment being successful .</p><p><strong>Scenario 2: Race condition</strong></p><ul><li>Instance 1 receives PaymentCompleted event and instance 2 receives OrderInitiated event both try to update the status in the DB at the same time, there will be a race condition and if OrderInitiated event finishes later, it wins and will overwrite the status and the data in the db.</li></ul><p>Result?</p><p>User sees outdated status OrderInitiated, and it might appear that the PaymentCompleted event is lost.</p><p>This kind of issues are very common in distributed systems and <strong>can lead to serious user-facing bugs</strong>.</p><h3>Solution</h3><p>Let’s discuss the solutions.</p><p>I Know the First Thing That Comes to Your Mind Is… Locks.</p><p>When we hear <strong>race conditions</strong>, our first instinct is:</p><p>“Let’s just lock the row while updating.”</p><p>Locks are not the best thing to do, but, let’s explore <strong>locking-based approaches</strong> first — both <strong>pessimistic </strong>and <strong>optimistic</strong>.</p><p><strong>🛠️ Option 1: Locking Approaches</strong></p><p><strong>A. Pessimistic Locking</strong></p><p>This approach involves acquiring a db level <strong>lock on the row</strong> after reading the row until the update completes and the transaction is committed. This is done using SELECT ... FOR UPDATE.</p><p>Until the transaction completes or rollbacks, all other transactions(from other instances of Query service) willing to update the row will be blocked from reading the row.</p><pre>BEGIN;<br>SELECT * FROM order_status WHERE order_id = &#39;ORD123&#39; FOR UPDATE;<br>-- check stage and timestamp<br><br>UPDATE order_status SET stage = ?, timestamp = ? WHERE order_id = &#39;ORD123&#39;;<br>COMMIT;</pre><p>This solves the race condition successfully, but still we will have to handle event sequencing by checking if the current status in db has sequence lower than the sequence of incoming event’s status, only then update.</p><pre>public enum OrderStatus {<br>ORDER_PLACED, // sequence 0<br>PAYMENT_COMPLETED, // sequence 1<br>PACKED, // sequence 2<br>SHIPPED; // sequence 3<br><br> public boolean isAfter(OrderStatus other) {<br> return this.ordinal() &gt; other.ordinal();<br> }<br>}</pre><pre>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Isolation;<br>import org.springframework.transaction.annotation.Transactional;<br><br>@Service<br>public class OrderService {<br><br> private final JdbcTemplate jdbcTemplate;<br><br> public OrderService(JdbcTemplate jdbcTemplate) {<br> this.jdbcTemplate = jdbcTemplate;<br> }<br><br> @Transactional(isolation = Isolation.READ_COMMITTED)<br> public void updateOrderStatus(String orderId, OrderStatus newStatus) {<br> <br> // Fetch current status with row-level update lock<br> String selectSql = &quot;SELECT status FROM orders WHERE id = ? FOR UPDATE&quot;;<br> OrderStatus currentStatus = jdbcTemplate.queryForObject(<br> selectSql,<br> new Object[]{orderId},<br> (rs, rowNum) -&gt; OrderStatus.valueOf(rs.getString(&quot;status&quot;))<br> );<br><br> <br> if (newStatus.isAfter(currentStatus)) {<br> String updateSql = &quot;UPDATE orders SET status = ? WHERE id = ?&quot;;<br> jdbcTemplate.update(updateSql, newStatus.name(), orderId);<br><br> }<br><br> // always save in history table if status is older or newer<br> String historySql = &quot;INSERT INTO order_history(order_id, status) VALUES (?, ?)&quot;;<br> jdbcTemplate.update(historySql, orderId, newStatus.name());<br> <br> }<br>}</pre><p><strong>Cons :</strong></p><ul><li>Adds overhead on the database, can also cause deadlocks.</li><li>Doesn’t scale well with Kafka’s parallel consumption model.</li><li>Bad for distributed systems (microservices), as it blocks all other instances until the transaction completes.</li></ul><p><strong>B. Optimistic Locking</strong></p><p>This strategy assumes most operations won’t conflict. So instead of blocking it lets them try their luck. We have to add a version column to our table, and during update, we <strong>check if the version is same as what we got during read(SELECT)</strong>. If not, that means it is updated in between, hence we need to retry.</p><pre><br><br>        String updateSql = &quot;<br>                UPDATE orders<br>                SET status = ?, version = version + 1<br>                WHERE id = ? AND version = ?<br>                &quot;;<br><br>        int rowsUpdated = jdbcTemplate.update(updateSql, newStatus, orderId, versionDuringSelect);<br><br>        if (rowsUpdated == 0) {<br>            throw new OptimisticLockingFailureException(<br>                    &quot;Order &quot; + orderId + &quot; was updated by another transaction&quot;<br>            );<br>        }<br>    }</pre><p><strong>Optimistic locks perform better than Pessimistic locks in cases of low conflict, as there is no blocking and hence high throughput.</strong></p><p><strong>Cons :</strong></p><ul><li>If conflicts are frequent retries kill performance.</li><li>More complex retry logic might be needed.</li></ul><p>This is why locks are not a good scalable solution.</p><h4>🗃️ Option 2: Store All Events &amp; Reconstruct (Event Log Replay)</h4><p>Instead of just storing the current status, Query service can <strong>store every event</strong> it receives and then <strong>build the latest status</strong> by ordering them during read or via a background processor.</p><p><strong>Pros</strong>:</p><ul><li>No information is lost</li><li>We get full audit/history</li></ul><p><strong>Cons</strong>:</p><ul><li>Requires more storage</li><li>More complex logic to compute current state</li></ul><h4>🧲 <strong>Option 3:</strong> <strong>Send All Events to the Same Kafka Partition (Efficient approach)</strong></h4><p>Kafka guarantees message order <strong>within a single partition of a single topic</strong>. A common idea is to use this to prevent race conditions and ensure proper ordering.</p><p><strong>But here’s the twist</strong>:<br> If services publish to different topics (even with same partition key — like orderId), Kafka <strong>doesn’t guarantee message ordering across topics</strong>.</p><p>So what do we do?</p><p>➤ One solution:</p><p>Introduce an <strong>order.aggregate topic</strong>.</p><p>Each service publishes normally to its own topic. A dedicated processor consumes all of them and republishes to this aggregate topic using the same key (orderId). Now all events for an order will go to <strong>the same partition of one single topic- order.aggregate</strong>.</p><p>Now Because all messages for a given order are in same partition, all the messages for that order will only be processed by 1 single instance. Hence, there will be no chance of race condition.</p><p>➤ But sequencing is still not guaranteed:</p><p>Message <strong>C (e.g., inventory)</strong> might get published before <strong>B (e.g., payment)</strong> to the aggregate topic because of the order in which they were received by the processor due to processing speed or network delay.</p><p>✅ Solution:</p><p>We can assign <strong>sequence number</strong> to the stages. Exactly like we did using OrderStatus Enum in the pessimistic lock approach. Update only if newStatus.isAfter(currentStatus).</p><p>In Service Q, when consuming from order.aggregate:</p><ul><li>Check the sequence.</li><li>If it’s <strong>ahead</strong> of the current stage → <strong>update status</strong>.</li><li>If it’s <strong>behind or same</strong> → <strong>store in history</strong>, skip update.</li></ul><p>This makes our system: <strong>Idempotent </strong>and<strong> Race-decoupled</strong></p><h4><strong>🧠 Option 4: Conditional Update (Easiest and Possibly the Best)</strong></h4><p>Skip locking entirely — just use a conditional update in a single query:</p><pre>UPDATE orders<br>SET status = ?, timestamp = ?<br>WHERE request_id = ?<br>  AND timestamp &lt; ?;</pre><p>That’s it !! Yes you read it right. This one query will solve our race condition problem, as well as out-of-order problem and we don’t even need to check the current status in db i.e. no SELECT query is required.</p><p>NOTE — Timestamp here is the time of generation of the event from source, example Payment completion time.</p><p>I know you might be thinking this can solve the out-of-order issue but how will it solve race condition issue.</p><p>Let’s verify, assuming message 2 and 3 arrived at the same time in 2 instances of query service. If query for message 3 executes just before message 2, so because current timestamp in db is of message 1, it satisfies the query condition (timestamp of message 1 &lt; timestamp of message 3) hence status and Timestamp will be updated, but now when message 2 executes the query (timestamp of message 3 &gt; timestamp of message 2) hence query will not be executed and data will not be overridden.</p><p><strong>Pros</strong>:</p><ul><li>No locks</li><li>Atomic and safe</li><li>Lightweight and scalable</li></ul><p><strong>Cons</strong>:</p><ul><li>Requires timestamp to be very consistent across all services and instances.</li><li>Doesn’t prevent all races, but ensures correctness via condition</li></ul><h4>📘 Final Thoughts</h4><p>Event-driven architectures are powerful, but they also shift the burden of correctness onto you. Never assume events will arrive in order — especially when multiple services, topics, and instances are involved.</p><p>By choosing the right approach — conditional updates, aggregate topic with partitioning, event logs, or controlled locking — we can build <strong>resilient and accurate</strong> systems on Kafka.</p><p>Have you faced this kind of issue in production? Which strategy worked for you? Let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2a61c44957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading at Light Speed: How Exchanges Process Orders with Microsecond Latency (Part- 1)]]></title>
            <link>https://medium.com/@sanskaragr.14/trading-at-light-speed-how-exchanges-process-orders-with-microsecond-latency-part-1-2c70e748c984?source=rss-8edbc55dcdc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c70e748c984</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[latency-optimization]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[trading-system]]></category>
            <dc:creator><![CDATA[Sanskar agrawal]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 23:39:03 GMT</pubDate>
            <atom:updated>2025-07-09T19:22:34.810Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trading at Light Speed: How Exchanges Process Orders with Microsecond Latency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rrZlhZPt9HfX-Mr7" /></figure><p>I’ve always wondered how order matching systems in stock exchanges work with such astonishingly low latency — even as millions of orders pour in every second, thousands of stocks are traded simultaneously, and prices change every few milliseconds. Each time a price moves, how does the exchange instantly re-evaluate all those orders to see if any now match?</p><p>So let’s take a closer look at how exchanges actually work behind the scenes.</p><h3>The Big Picture: What Happens When You Place an Order?</h3><p>Whenever you click <em>Buy</em> or <em>Sell</em> on your trading app, your order travels across the internet and ends up in the exchange’s <strong>order matching engine</strong>.</p><p>This engine has one main job:<br> <strong>Find if there’s someone on the opposite side of the trade willing to accept the terms you offered.</strong></p><p>Here’s the basic idea:</p><ul><li>Every buy order includes the maximum price the buyer is willing to pay (<strong>bid</strong>).</li><li>Every sell order includes the minimum price the seller is willing to accept (<strong>ask</strong>).</li><li>The exchange keeps two lists per instrument:</li><li>The <strong>bid book</strong>, sorted by price descending (best bid on top).</li><li>The <strong>ask book</strong>, sorted by price ascending (best ask on top).</li><li>If the highest bid is greater than or equal to the lowest ask, a match occurs, and the trade is executed.</li></ul><p>This matching happens <strong>only when new orders arrive</strong> or existing orders are canceled or modified — not every time the market price changes somewhere else. It is the humans who modify their orders or place new orders on price change, <strong>system does not really depend on the current market price</strong>.</p><p>This process might sound simple, but doing it across thousands of instruments with massive order volumes requires careful design.</p><h3>⚙️ 1. Core Components of an Exchange</h3><p>Before we get into the algorithmic weeds, let’s understand the system architecture:</p><ul><li><strong>Order Entry Gateway</strong>: Receives orders via FIX protocol, WebSockets, or proprietary APIs. (what and why discussed later in the article)</li><li><strong>Order Book / Matching Engine</strong>: The central piece that matches buy/sell orders.</li><li><strong>Market Data Publisher</strong>: Publishes market data feeds (order book changes) to all subscribers.</li><li><strong>Risk Check Engine</strong>: Ensures clients have margin or exposure limits before accepting orders.</li><li><strong>Persistence Layer</strong>: Stores trade confirmations, audit trails, and snapshots.</li></ul><h3>⚡ 2. The Challenge: High Throughput + Low Latency</h3><p>dealing with:</p><ul><li>Millions of messages per second.</li><li>Thousands of instruments (stocks, futures, options).</li><li>Price updates every microsecond (especially with HFT players).</li><li>Matching engines with &lt;10µs latency.</li></ul><p>Achieving this demands extreme optimization in <strong>both software and hardware</strong>.</p><h3>🧠 3. Order Matching Algorithm and Data structure</h3><p>Most exchanges use a variant of what’s called <strong>Price-Time Priority</strong>:</p><ol><li><strong>Price priority</strong>: The best price gets matched first.</li><li><strong>Time priority</strong>: If multiple orders are at the same price, the earliest one in the queue gets matched first.</li></ol><h4>a. Order Book Representation</h4><ul><li><strong>Two Trees or Heaps</strong>:</li><li>One for <strong>bids</strong> (max-heap or red-black tree ordered by price descending).</li><li>One for <strong>asks</strong> (min-heap or red-black tree ordered by price ascending).</li><li>Each price level has a <strong>FIFO queue</strong> for time-priority ordering.</li></ul><h4>b. Data Structures in Use</h4><ul><li>Map&lt;Double, Queue&lt;Order&gt;&gt; for price-level mapping.</li><li><strong>Memory-mapped files</strong> for persistence without disk I/O latency.</li></ul><h3>⏱️ 4. Latency Optimizations</h3><ul><li><strong>Zero-GC languages</strong> like C++ or custom JVMs with tuned GC.</li><li><strong>Lock-free algorithms</strong>: Avoids thread contention.</li><li><strong>Hardware Timestamping</strong> and <strong>Clock Synchronization</strong> for microsecond precision.</li><li><strong>NUMA-aware memory allocation</strong>.</li></ul><p><strong>NUMA</strong> = <strong>Non-Uniform Memory Access. </strong>This is a <strong>computer architecture</strong> used in modern multi-socket servers (i.e., servers with more than one CPU).</p><ul><li>In <strong>NUMA systems</strong>: The machine has <strong>multiple CPUs (“sockets” or “nodes”)</strong>. <strong>Each CPU has its own local memory (RAM)</strong> physically attached to it.</li><li>CPUs <em>can</em> still access memory attached to other CPUs, but <strong>accessing remote memory is slower</strong>.</li><li>Hence in trading systems to keep uniform and faster memory access times, allocations are done to avoid accessing remote RAM, instead all information is stored in local RAM.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F3xuFsh_eJo-yc5s" /></figure><p>Now lets discuss what are FIX and WebSocket protocols and why they are used in trading instead of HTTP.</p><h4><strong>FIX</strong> Protocol (Financial Information Exchange)</h4><p>It is a simple and standard protocol to let brokers, exchanges, and trading firms <strong>speak the same “language.”</strong></p><p>✅ It is a<strong> standard message format</strong> for orders, cancels, executions with A <strong>text-based encoding</strong> over TCP.</p><p>✅ <strong>Simple FIX order message-</strong></p><p>8=FIX.4.2|9=176|35=D|49=CLIENT1|56=EXCHANGE|34=2|11=ORDER123|<br>21=1|55=INFY|54=1|60=20240610–12:34:56|38=100|40=2|44=1550.00|10=128|</p><p>Each tag has a specific meaning<br>35=D: Message Type = New Order Single</p><p>49: SenderCompID (who sent it)</p><p>56: TargetCompID (who gets it)</p><p>11: ClOrdID (client’s order ID)</p><p>55: Symbol (instrument)</p><p>54: Side (1=Buy)</p><p>38: Quantity</p><p>44: Price</p><p>10: Checksum</p><h4>WebSocket</h4><p>It is a <strong>modern internet protocol</strong> for <strong>real-time, bidirectional communication</strong> over a single TCP connection.</p><p>✅ Invented to allow web apps to <strong>maintain an open connection to a server.</strong></p><p>✅ Once the connection is made. The connection stays open.</p><p>✅ Both sides can <strong>send messages any time</strong> — like a phone call, instead of letters.</p><p><strong>💡 Why Do We Use WebSocket in Trading?</strong></p><p>Because trading platforms need:</p><ul><li><strong>Real-time price updates</strong> (tick-by-tick).</li><li><strong>Instant notifications</strong> about order status.</li><li><strong>Low latency</strong> between order placement and acknowledgment.</li></ul><p>Polling with HTTP (GET every second) is:<br> ❌ Slow<br> ❌ Inefficient (lots of redundant requests)<br> ❌ Prone to missing fast-changing data.</p><p>WebSocket solves this by pushing updates <strong>as soon as they happen</strong>.</p><p>Before we move on, here’s something to think about: In trading platforms where millions of orders flow in every second, how many servers do you think are needed to handle all that load? And how many threads are actually created behind the scenes to keep everything running smoothly?</p><p>Take a moment to imagine it —Feel free to scroll down once you are ready.</p><h3>🧠 1️⃣ How Many Servers?</h3><p>This varies hugely by exchange size and design.</p><ul><li>A <em>smaller regional exchange</em> might run all matching engines on <strong>8–10 high-end servers.</strong></li><li>A <em>large exchange</em> (like NASDAQ) might run <strong>hundreds of matching engine servers</strong>.</li></ul><p>For perspective:</p><ul><li><strong>NASDAQ</strong> says they process ~500,000+ messages per second <strong>per engine</strong>, and they have dozens of engines.</li></ul><h3>🧵 2️⃣ How Many Threads per Server?</h3><p>This is really interesting:</p><p>Order Matching engine design aims for<strong> determinism, not maximal concurrency </strong>and therefore<strong> the answer is 1 per stock. </strong>Obviously they have few other separate threads for handling non core functionalities like<strong> — </strong>network IO, persistence logging, monitoring and risk checks.</p><p>So assuming 24-core CPU, 6–8 threads are only used per engine process.</p><h3>⚡ So how do you utilize many cores?</h3><p><strong>You partition by stock.</strong></p><p>Instead of 1 giant order book shared across all cores, you do something like:</p><p>Each core has:</p><ul><li><strong>Its own thread and handles just 1 specific stock</strong></li><li><strong>Its own order book data in memory i.e. RAM ( during processing data gets loaded in L1 or L2 cache of the core).</strong></li><li><strong>No need to lock or share data with other cores.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X8hoIj9JzcmDdU5n" /></figure><h3>🧠 Think of it like this:</h3><ul><li>There is <strong>dedicated CPU core</strong> handling <strong>only 1 of the stock</strong> with its own dedicated (non shared) order book.</li><li>That core runs <strong>one single-threaded loop</strong>.</li><li>The loop:</li></ul><ol><li>Reads the next message from a queue (network ring buffer).</li><li>Processes it (match/cancel/update book).</li><li>Publishes the response.</li><li>Repeats.</li></ol><p>Because there is:</p><ul><li><strong>No context switching</strong></li><li><strong>No locking</strong></li><li><strong>No CPU cache thrashing</strong></li></ul><p>…it can process a single message in <strong>~1–2 microseconds.</strong></p><h3>🏗️ Why not create multiple request threads, similar to what most of the microservices today do?</h3><p>That would be <em>much</em> slower. Here’s why:</p><ul><li>Creating threads for each message adds <strong>huge overhead</strong>:</li><li>Thread creation = ~microseconds to milliseconds.</li><li>Context switching = ~1000+ cycles each time.</li><li>Synchronization between threads introduces locking, which increases latency</li><li>We lose <strong>strict ordering</strong>, which is critical for fairness in trading.</li></ul><h3>📊 Example Throughput Math</h3><p>Let’s see the math:</p><p><strong>Example:</strong></p><ul><li>A matching engine processes one message in <strong>~1.5 microseconds</strong> (µs).</li></ul><p>1 second = 1,000,000 µs<br> 1,000,000 / 1.5 = ~666,666 messages/sec</p><ul><li>That’s <strong>666,666 messages per second</strong> theoretical throughput per thread.</li></ul><p><strong>That’s how we get the claim of 500,000+ messages/sec per engine.</strong></p><p>Thanks for reading. Please add feedbacks, suggestions and questions in the comments, happy to discuss and learn more on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c70e748c984" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>