<?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 Shekinah on Medium]]></title>
        <description><![CDATA[Stories by Shekinah on Medium]]></description>
        <link>https://medium.com/@shekinahmgdavid?source=rss-cfba44ca273a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k18TB5j_BeU7aRii</url>
            <title>Stories by Shekinah on Medium</title>
            <link>https://medium.com/@shekinahmgdavid?source=rss-cfba44ca273a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:25:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shekinahmgdavid/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[Exactly-Once Delivery Is Mostly a Myth]]></title>
            <link>https://medium.com/@shekinahmgdavid/exactly-once-delivery-is-mostly-a-myth-36b21c4391d3?source=rss-cfba44ca273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b21c4391d3</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[payment-systems]]></category>
            <category><![CDATA[deduplication]]></category>
            <category><![CDATA[exactly-once-processing]]></category>
            <dc:creator><![CDATA[Shekinah]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 13:17:06 GMT</pubDate>
            <atom:updated>2026-04-20T13:17:06.883Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the first lessons you learn when building distributed systems is that <strong>exactly-once delivery is mostly a myth</strong>.</p><p>Most real-world messaging systems — whether it’s <strong>Apache Kafka</strong>, <strong>RabbitMQ</strong>, or any other broker — typically provide <strong>at-least-once delivery guarantees</strong>.</p><p>This means the system guarantees that a message will be delivered, but it does not guarantee that it will only be delivered once.</p><p>Messages can be redelivered for many reasons:</p><ul><li>a consumer crashes before acknowledging a message</li><li>the broker retries delivery after a network timeout</li><li>a service is redeployed while messages are in flight</li><li>events are replayed for recovery or backfills</li></ul><p>From the perspective of a consumer, <strong>duplicate events are not edge cases — they are a normal part of operating a distributed system</strong>.</p><p>Because of this, reliable event-driven architectures depend heavily on one important design principle:</p><blockquote><em>Consumers must be idempotent.</em></blockquote><p>An <strong>idempotent consumer</strong> ensures that processing the same event multiple times results in the same outcome as processing it once.</p><p>In the rest of this article, I’ll walk through how our consumer evolved toward an idempotent design — starting from a simple approach and gradually improving it to handle the realities of production systems.</p><h3>Designing an Idempotent Consumer in an Event-Driven System</h3><p>When building event-driven systems, one rule becomes clear very quickly:</p><p><strong>Duplicate events are inevitable.</strong></p><p>Most message brokers such as <strong>Apache Kafka</strong> or <strong>RabbitMQ</strong> provide <strong>at-least-once delivery guarantees</strong>. This means the broker ensures that messages are delivered, but it does not guarantee that they will only be delivered once.</p><p>If a consumer crashes before acknowledging a message, the broker will redeliver it. Retries, replays, DLQ processing, or network interruptions can also cause the same event to appear multiple times.</p><p>Because of this, consumers must be designed to be <strong>idempotent</strong>.</p><p>An <strong>idempotent consumer</strong> ensures that processing the same event multiple times results in the same outcome as processing it once.</p><p>In this article, I’ll walk through how our consumer evolved toward an idempotent design and some of the practical considerations that came with it.</p><h3>The Problem With Duplicate Events</h3><p>Consider a typical event consumed from the broker:</p><pre>PaymentCreatedEvent<br>{<br>  eventId: evt_90213<br>  orderId: ord_11<br>  amount: 500<br>}</pre><p>If the consumer processes this event twice, the consequences can be severe depending on the domain:</p><ul><li>a payment might be charged twice</li><li>an order might be created twice</li><li>inventory might be reduced twice</li></ul><p>Preventing these situations is the responsibility of the <strong>consumer</strong>, not the message broker.</p><p>The most common solution is to track which events have already been processed.</p><h3>Introducing an Idempotency Table</h3><p>The simplest approach is to store processed event identifiers in a dedicated table.</p><pre>processed_events<br>-------------------------<br>event_id<br>processed_at</pre><p>Every time the consumer processes an event, it records the event ID in this table.</p><p>The consumer flow looks like this:</p><ol><li>Receive the event</li><li>Check whether the event ID already exists</li><li>If it exists → skip processing</li><li>If it does not → process the event and record it</li></ol><p>While the idea is simple, the implementation details matter.</p><p>A naive implementation might perform a <strong>check-then-insert</strong>, but this introduces race conditions when multiple consumers process events concurrently.</p><p>Instead, we rely on the database to guarantee uniqueness.</p><h3>Exception-Driven Deduplication</h3><p>In the first implementation, the event_id column had a <strong>unique constraint</strong>. The consumer attempted to insert the event ID into the idempotency table, and if the event had already been processed, the database would throw an exception.</p><p>The logic looked something like this:</p><pre>@Transactional<br>public void handleEvent(Event event) {<br><br>    try {<br><br>        processedEventRepository.insert(event.getEventId());<br><br>        processBusinessLogic(event);<br><br>    } catch (DuplicateKeyException ex) {<br>        return;<br>    }<br>}</pre><p>This works because the database ensures that the same event ID cannot be inserted twice.</p><p>If the insert succeeds, we process the event.<br> If the insert fails due to a unique constraint violation, we know the event has already been handled.</p><p>Although this approach is correct, it has a couple of drawbacks.</p><p>First, it relies on <strong>exceptions for normal control flow</strong>. In distributed systems, duplicate events are expected, not exceptional.</p><p>Second, duplicate events generate unnecessary exception logs, which can pollute monitoring and observability systems.</p><p>This pushed us toward a cleaner approach.</p><h3>Moving to INSERT IGNORE</h3><p>Instead of relying on exceptions, we shifted to a database operation that silently ignores duplicates.</p><p>Many relational databases support variants of this pattern. In MySQL, for example, the query can be written as:</p><pre>INSERT IGNORE INTO processed_events(event_id, processed_at)<br>VALUES (?, NOW());</pre><p>If the event ID does not exist, the row is inserted.</p><p>If the event ID already exists, the insert is simply ignored.</p><p>This makes the consumer logic much cleaner because the database returns the number of rows affected.</p><h3>Making Idempotency Truly Safe: Atomic Processing</h3><p>Idempotency isn’t just about skipping duplicates — it’s about <strong>ensuring correctness under failures</strong>.</p><p>A subtle but critical issue arises if the idempotency check and business logic are not atomic:</p><pre>INSERT IGNORE → success<br>business logic → fails</pre><p>In this case, the event is marked as processed but the actual work never completed. On retry, the event will be skipped — leading to <strong>data inconsistency</strong>.</p><p>To avoid this, both steps must run in the <strong>same transaction</strong>.</p><p>With this approach, the consumer workflow becomes very straightforward:</p><ol><li>Receive the event</li><li>Attempt to insert the event ID into the idempotency table</li><li>If one row was inserted → process the event</li><li>If zero rows were inserted → skip the event</li></ol><p>The code becomes easier to reason about:</p><pre>@Transactional<br>public void handleEvent(Event event) {<br><br>    int inserted = processedEventRepository.insertIgnore(event.getEventId());<br><br>    if (inserted == 0) {<br>        return;<br>    }<br><br>    processBusinessLogic(event);<br>}</pre><p>The repository query might look like this:</p><pre>@Modifying<br>@Query(<br> value = &quot;&quot;&quot;<br> INSERT IGNORE INTO processed_events(event_id, processed_at)<br> VALUES (:eventId, NOW())<br> &quot;&quot;&quot;,<br> nativeQuery = true<br>)<br>int insertIgnore(@Param(&quot;eventId&quot;) String eventId);</pre><p>The database effectively becomes the <strong>deduplication mechanism</strong>, ensuring that two concurrent consumers cannot process the same event.</p><h3>A Note on Design Tradeoffs</h3><p>In distributed systems there is rarely a single universal solution. The idempotency table pattern works well when a consumer handles many different event types or when business operations are complex updates rather than simple inserts.</p><p>However, experienced engineers sometimes consider a different approach: <strong>embedding idempotency directly into the business data model.</strong></p><p>Instead of maintaining a separate processed_events table, the event identifier can be stored in the business record itself and protected with a unique constraint.</p><p>For example:</p><pre>payments<br>------------------------------<br>payment_id<br>order_id<br>amount<br>event_id (UNIQUE)<br>created_at</pre><p>When the consumer processes an event, the business insert itself acts as the idempotency check. If the same event is delivered again by <strong>Apache Kafka</strong> or <strong>RabbitMQ</strong>, the unique constraint prevents the operation from executing twice.</p><p>This approach removes the need for a separate idempotency table, but <strong>it only works well when events create new records</strong>. For systems where events frequently update existing state, maintaining a dedicated idempotency store is often simpler and more consistent.</p><h3>The Operational Problem Nobody Mentions</h3><p>There is one practical challenge with idempotency tables that is easy to overlook.</p><p>They <strong>grow forever</strong>.</p><p>If a system processes millions of events per day, the processed_events table can quickly become massive. Over time this leads to:</p><ul><li>larger indexes</li><li>slower writes</li><li>increased storage costs</li><li>slower backups and replication</li></ul><p>In practice, idempotency only needs to be guaranteed within the <strong>event replay window</strong>.</p><p>For example, if the broker retains messages for three days, duplicates are unlikely to appear beyond that timeframe.</p><p>Because of this, most systems implement a <strong>retention policy</strong> for idempotency records.</p><p>A <strong>simple cleanup job </strong>might periodically remove old entries one by one or in batches :</p><pre>DELETE FROM processed_events<br>WHERE id IN (<br>    SELECT id FROM processed_events<br>    WHERE created_at &lt; NOW() - INTERVAL 7 DAY<br>    LIMIT 1000<br>);</pre><p>At larger scale, teams often use <strong>table partitioning by date</strong> and drop entire partitions instead of deleting rows. This keeps the table size predictable while maintaining the idempotency guarantee.</p><h3>Scheduling Cleanup Safely in a Distributed System</h3><p>Cleanup is typically run as a scheduled job, for example once a day during off-peak hours.</p><p>In production, multiple instances of the same service run in parallel. This creates a problem for scheduled jobs:</p><pre>Instance A → runs cleanup  <br>Instance B → also runs cleanup  <br>Instance C → also runs cleanup  </pre><p>Even if the job is idempotent, this leads to unnecessary database load and contention.</p><p>We use <strong>ShedLock</strong> to coordinate execution across instances using the database.</p><pre>@Configuration<br>@EnableSchedulerLock(defaultLockAtMostFor = &quot;10m&quot;)<br>public class ShedLockConfig {<br><br>    @Bean<br>    public JdbcTemplateLockProvider lockProvider(DataSource dataSource) {<br>        return new JdbcTemplateLockProvider(<br>                JdbcTemplateLockProvider.Configuration.builder()<br>                        .withJdbcTemplate(new JdbcTemplate(dataSource))<br>                        .usingDbTime()<br>                        .build()<br>        );<br>    }<br>}</pre><pre>@Scheduled(cron = &quot;0 0 3 * * *&quot;)<br>@SchedulerLock(name = &quot;idempotency_cleanup_job&quot;)<br>public void cleanupOldIdempotencyRecords() {<br>    // batch delete logic<br>}</pre><p>Without coordination:</p><ul><li>multiple instances execute the same job</li><li>database load spikes unnecessarily</li><li>system behavior becomes unpredictable</li></ul><p>With distributed locking:</p><ul><li>only one instance owns the job</li><li>execution is controlled and predictable</li><li>the system scales safely</li></ul><p>In distributed systems, coordination is as important as correctness. Even idempotent jobs should be controlled to avoid unnecessary load and contention.</p><h3>Choosing the Right Locking Strategy</h3><p>While a database-backed approach using ShedLock works well for most scheduled jobs, distributed locking strategies typically evolve with system scale.</p><p>In high-throughput systems where lock contention is frequent, teams often move to in-memory solutions like Redis-based locks, which offer lower latency and better performance. For systems that require stronger coordination guarantees — such as leader election or managing complex distributed workflows — tools like Apache ZooKeeper are commonly used.</p><p>In practice, the choice of locking mechanism is a trade-off between simplicity, performance, and coordination needs: database locks for reliability and ease of use, Redis for speed at scale, and Zookeeper for robust distributed coordination.</p><h3>Final Thoughts</h3><p>Idempotent consumers are one of those design patterns that seem straightforward at first but reveal deeper considerations as systems scale.</p><p>The evolution we went through was fairly typical:</p><ul><li>start with a simple deduplication idea</li><li>rely on database constraints for safety</li><li>move away from exception-driven logic</li><li>adopt database operations like INSERT IGNORE for cleaner control flow</li><li>eventually think about operational concerns such as table growth</li></ul><p>What makes idempotency interesting is that it sits at the intersection of <strong>application design, database guarantees, and distributed system behavior</strong>.</p><p>Message brokers can retry messages.<br> Consumers can crash and restart.<br> Events can be replayed months later.</p><p>The system stays correct only if the consumer is designed to safely handle all of these situations.</p><p>In practice, that means building consumers that assume duplicates are normal and designing the system so that <strong>processing the same event twice simply doesn’t matter</strong>.</p><p>Once that property is in place, many other parts of the architecture — retries, recovery mechanisms, and replay strategies — become significantly easier to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b21c4391d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolving an Idempotent Payment System]]></title>
            <link>https://medium.com/@shekinahmgdavid/evolving-an-idempotent-payment-system-c264354383a9?source=rss-cfba44ca273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c264354383a9</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[payment-systems]]></category>
            <dc:creator><![CDATA[Shekinah]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 10:43:53 GMT</pubDate>
            <atom:updated>2026-04-09T10:43:53.419Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Reliable payment systems are rarely built in a single design. They evolve through a series of bottlenecks, failures, and architectural adjustments.</strong></h3><p>Modern payment systems must guarantee <strong>exactly-once processing</strong> even when clients retry requests due to network failures, timeouts, or partial failures in distributed systems.</p><p>At first glance, this sounds straightforward: accept a payment request, process it, and return a response. But the moment retries, concurrency, and event-driven architectures enter the picture, things become significantly more complex.</p><p>In this series, I explore how an <strong>idempotent payment system evolves</strong> from a simple implementation into a more scalable architecture capable of handling increasing throughput.</p><p>This first article walks through the <strong>evolution of the system</strong>, the bottlenecks encountered along the way, and the architectural optimizations that followed.</p><h3>The System We Want to Build</h3><p>At a high level, the system processes payment requests while ensuring the same payment request is <strong>never processed twice</strong>.</p><p>This is typically achieved using an <strong>idempotency key</strong>.</p><p>The client sends a unique key with each payment request. If the request is retried due to a timeout or network failure, the system detects the duplicate key and returns the original result instead of processing the payment again.</p><p>This guarantees safe retries.</p><p>The API persists the payment, writes an event to an <strong>outbox table</strong>, and eventually publishes that event to Kafka.</p><p>This approach ensures that <strong>database state and events remain consistent</strong>, a pattern commonly known as the <strong>Outbox Pattern</strong>.</p><h3>The First Implementation: A Simple MVP</h3><p>The first version of the system was intentionally simple.</p><p>The API performs three steps within a single transaction:</p><ol><li>Validate the idempotency key</li><li>Insert the payment record</li><li>Insert an outbox event</li></ol><p>Later, a scheduled job scans the outbox table and publishes events to Kafka.</p><p>Conceptually, this looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*Mbbg64dhGtJR3ALH2d1iDA.png" /><figcaption>mvp flow</figcaption></figure><p>For an MVP, this works well.</p><p>The system guarantees:</p><ul><li>No duplicate payments</li><li>Reliable event publishing</li><li>Consistent database state</li></ul><p>However, the moment concurrency enters the picture, new problems appear.</p><h3>The First Challenge: Concurrency</h3><p>Imagine multiple requests arriving with the same idempotency key due to client retries.</p><p>Without proper protection, two threads could process the same request simultaneously.</p><p>To prevent this, the system introduced <strong>row-level locking</strong> when retrieving events from the outbox table.</p><p>A query similar to the following ensures only one worker processes a given row:</p><pre>SELECT * <br>FROM outbox_events<br>WHERE status = &#39;NEW&#39;<br>ORDER BY created_at<br>LIMIT 10<br>FOR UPDATE SKIP LOCKED</pre><p>This pattern is widely used in high-throughput systems because it allows multiple workers to process events concurrently while avoiding conflicts.</p><p>The system now became <strong>safe under concurrency</strong>.</p><p>But a new bottleneck appeared.</p><h3>The Next Bottleneck: Long Database Transactions</h3><p>Initially, the system would:</p><ol><li>Lock the outbox rows</li><li>Publish events to Kafka</li><li>Update their status</li></ol><p>All within the <strong>same transaction</strong>.</p><p>This meant the database transaction stayed open while waiting for Kafka acknowledgements.</p><p>In high-throughput systems, long-running transactions create serious problems:</p><ul><li>Increased lock contention</li><li>Reduced database throughput</li><li>Higher latency under load</li></ul><p>The fix was simple but important.</p><p>Instead of holding the transaction open during Kafka publishing, the system was redesigned to use <strong>status-based transitions</strong>.</p><p>The flow became:</p><pre>NEW → PROCESSING → PROCESSED</pre><p>The publisher now performs two short transactions:</p><ol><li>Fetch and mark events as PROCESSING</li><li>Publish events to Kafka</li><li>Mark them as PROCESSED</li></ol><p>This drastically reduced <strong>transaction duration</strong> and improved database performance.</p><h3>The Next Optimization: Kafka Publishing Throughput</h3><p>Another issue became visible as the system matured.</p><p>Each event was being published to Kafka <strong>sequentially</strong>.</p><p>This introduces unnecessary latency, because Kafka clients support asynchronous publishing.</p><p>Instead of sending events one by one and waiting for each acknowledgement, the publisher now sends events concurrently using <strong>CompletableFuture</strong>.</p><p>Conceptually:</p><pre>Event 1 → Kafka<br>Event 2 → Kafka<br>Event 3 → Kafka<br>Event 4 → Kafka</pre><p>All requests are sent <strong>in parallel</strong>, and the system waits for them collectively.</p><p>This improves throughput significantly while maintaining reliability.</p><p>In practice, this approach allows the publisher to handle <strong>much larger event batches</strong> without blocking on individual sends.</p><h3>Where the System Stands Now</h3><p>At this point, the system has evolved considerably from its original MVP.</p><p>It now supports:</p><ul><li>Idempotent payment processing</li><li>Reliable event publishing via the outbox pattern</li><li>Safe concurrent processing using row-level locking</li><li>Reduced transaction duration with status transitions</li><li>Improved throughput with asynchronous Kafka publishing</li></ul><p>For many systems, this architecture is <strong>more than sufficient</strong>.</p><p>But one limitation still remains.</p><p>The system relies on a <strong>polling mechanism</strong> to detect new events in the outbox table.</p><p>Polling works well at moderate scale, but as event throughput increases, it introduces inefficiencies.</p><ul><li>The database is constantly queried</li><li>Poll intervals add latency</li><li>Scaling requires more polling workers</li></ul><p>In high-scale event-driven architectures, there is a better approach.</p><h3>The Next Step: Removing Polling</h3><p>Instead of polling the database for new events, modern architectures often rely on <strong>Change Data Capture (CDC)</strong>.</p><p>CDC tools monitor database transaction logs and stream changes directly into event systems like Kafka.</p><p>One of the most widely used tools for this is <strong>Debezium</strong>.</p><p>With Debezium, the database itself becomes the source of events, eliminating the need for application-level polling entirely.</p><p>In the next article, we will explore how introducing <strong>Debezium</strong> fundamentally changes this architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c264354383a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>