<?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 Sahil Bajaj on Medium]]></title>
        <description><![CDATA[Stories by Sahil Bajaj on Medium]]></description>
        <link>https://medium.com/@sahilbajaj85?source=rss-b92473f53244------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sahil Bajaj on Medium</title>
            <link>https://medium.com/@sahilbajaj85?source=rss-b92473f53244------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:53:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sahilbajaj85/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[Unlocking the Secrets to Efficient Database Management]]></title>
            <link>https://medium.com/@sahilbajaj85/unlocking-the-secrets-to-efficient-database-management-b3a692dad84c?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3a692dad84c</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 07:38:28 GMT</pubDate>
            <atom:updated>2026-04-12T07:38:28.853Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been hearing about databases since our college days. It’s not just IT professionals, but people in product, operations, and almost every other field who have come across the term ‘database.’</p><p>But do you truly understand how a database works under the hood?</p><p>Let’s start with a high-level view. A database is essentially a storage engine — where we store information and retrieve it whenever needed. It’s the backbone of every system, playing a critical role in data management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*l8XAgIMynfI0jwGBrYYYYw.png" /></figure><p><strong>So, where do we store the data — RAM, SSD, or ROM?</strong></p><p>In reality, it’s a blend of all three. ROM provides durability, while RAM and SSD function as caches before the data is stored in ROM. So, data is first written to RAM, and then it is asynchronously synced to ROM.</p><p>This also means there are cases of <em>cache misses</em>, where the required data needs to be fetched from ROM.</p><p><strong>But wait, haven’t we heard that accessing data from ROM is a time-consuming operation?</strong></p><p>Yes, that’s true. And this is where <strong>indexing</strong> comes to the rescue. Every database stores metadata in RAM, which helps fetch data from ROM much faster. Think of this as maintaining a B+ tree, where references to actual records are stored based on some key.</p><p><strong>But wait! What happens if data is written to RAM and the system restarts before it gets saved to ROM? How does the database ensure durability?</strong></p><p>This is where the Write-Ahead Log (WAL) comes into play. WAL ensures that even if the system restarts, the data is already persisted in the log before confirming its persistence to the user. Once the data is safely in the WAL, it can then be written to ROM.</p><p>The WAL acts like a file where data is appended to the end of the previous entries. Because there’s no need for complex lookups, as is required for ROM inserts/updates, writing to the WAL is extremely fast.</p><p>Hmmm… thinking!</p><p><strong>What if the database node crashes completely and never recovers? Does that mean all my data is lost?”</strong></p><p>Great question!</p><p>This is where <strong>resiliency</strong> comes into play. I’m sure you’ve heard of concepts like <strong>master-slave</strong> or <strong>active-passive</strong> nodes. In this setup, one node acts as the master, handling all database operations, while one or more standby nodes replicate the same data. If the master node fails or crashes, one of the standby nodes can automatically take over as the new master, ensuring no data is lost and service continues seamlessly.</p><p><strong>But didn’t you say it’s a completely different node? So the data must be synced from the primary (master) node to it, right?</strong></p><p><strong>Yes, you’ve hit the nail on the head.</strong></p><p>The same <strong>Write-Ahead Log (WAL)</strong> that the primary node uses to ensure durability is also used to replicate data to the standby (slave/replica) nodes. This ensures that both primary and replica nodes stay in sync with the same sequence of changes.</p><p><strong>Okay. Even though we have master-slave architecture, at any given moment only the master is handling all operations until it fails. Doesn’t that put a lot of pressure on it since it handles both reads and writes?</strong></p><p><strong>Yes, absolutely.</strong></p><p>That’s where <strong>replica nodes</strong> become very important in real-world systems. To handle large-scale traffic, the workload is distributed — typically, writes go to the primary node, while reads are served from replica nodes. This helps balance the load and improves overall system performance and scalability.</p><p><strong>But having slave nodes is not a waste of resources, as they are just copying data but not serving any purpose until the master dies?</strong></p><p>Very good — you are now thinking in terms of efficiency. Yes, the concept of slave nodes has now become obsolete, and replica nodes have taken their place instead. So, when the master node dies, one of the replica nodes gets elected as the leader and becomes the primary node.</p><p>One last question!</p><p><strong>My system requires very high consistency of data. Based on what we have learned so far, there is a possibility that before data is replicated to the replica node, the master node crashes and the data is not yet updated in the replica’s WAL file.</strong></p><p>True — that is a valid concern.</p><p>So, for such systems, we have the concept of write consistency levels. We can define durability as being confirmed to the user only once the data is copied to all nodes — both the master and all replica nodes. This helps achieve very high consistency.</p><p><strong>I have been working with Oracle databases for a long time, but I have never heard the term WAL. Did I miss anything?</strong></p><p>Good question. Let me connect the dots.</p><p>WAL is a concept commonly associated with PostgreSQL. In MySQL, a similar role is played by the binary log (binlog), and in Oracle, by the redo log. The general term that describes this concept across databases is the <em>change log</em>.</p><h3>Conclusion</h3><p>The information shared above is, to the best of my understanding, a deep overview of how data is actually stored in a database and how various components come together to serve that purpose.</p><p><em>Thanks for reading. Hope you enjoyed it!!!</em></p><p><strong>More Related Articles</strong></p><p><a href="https://medium.com/@sahilbajaj85/fifo-in-database-handling-786ce96b6bf5">FIFO in Database Handling</a></p><p><a href="https://medium.com/@sahilbajaj85/less-code-more-impact-scalable-exception-handling-03d90e9766ec">Less Code, More Impact: Scalable Exception Handling</a></p><p><a href="https://medium.com/@sahilbajaj85/graceful-synchronisation-for-concurrent-traffic-07380380604e">Graceful Synchronisation for Concurrent Traffic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a692dad84c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are We Making Life HARDER Than It Should Be?]]></title>
            <link>https://medium.com/@sahilbajaj85/are-we-making-life-harder-than-it-should-be-7b141caefac7?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b141caefac7</guid>
            <category><![CDATA[deep-thinking]]></category>
            <category><![CDATA[self-growth]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 12:38:48 GMT</pubDate>
            <atom:updated>2026-04-04T12:38:48.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Are we making life harder than it needs to be?</p><p>In a world where we are constantly chasing success, approval, and material goals, we often forget a simple truth — happiness was once natural to us. As children, we lived freely, joyfully, and without overthinking. So what changed?</p><p>This book takes you on a reflective journey to understand how our thoughts, expectations, and daily habits shape our happiness. It explores the difference between short-term pleasure and true, lasting peace — and how much of our struggle is created by our own mindset.</p><p>Through simple ideas, real-life observations, and practical steps, this book helps you understand how expectations influence your happiness and how your internal chemistry and mindset shape the way you feel and respond to life. It gently guides you to respond thoughtfully instead of reacting impulsively, to let go of overthinking and constant comparison, and to build small, meaningful habits that support a calm, peaceful, and balanced way of living.</p><p>If you are looking for a simpler, more meaningful way to live,<br>this book will help you pause, reflect, and reconnect with what truly matters.</p><p>Resources:</p><p>Amazon: <a href="https://www.amazon.in/Making-Life-HARDER-Than-Should/dp/B0GTL73G9Y">https://www.amazon.in/Making-Life-HARDER-Than-Should/dp/B0GTL73G9Y</a><br>Flipkart: <a href="https://www.flipkart.com/making-life-harder-than-should-be/p/itmdb989bf9e24e9">https://www.flipkart.com/making-life-harder-than-should-be/p/itmdb989bf9e24e9</a><br>Notion Press: <a href="https://notionpress.com/in/read/are-we-making-life-harder-than-it-should-be">https://notionpress.com/in/read/are-we-making-life-harder-than-it-should-be</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*_x4nyjPgmQRU9eIdYoiuZQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b141caefac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are You Someone Others Feel Safe With?]]></title>
            <link>https://medium.com/@sahilbajaj85/are-you-someone-others-feel-safe-with-245aa216bf2c?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/245aa216bf2c</guid>
            <category><![CDATA[emotional-intelligence]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[gratitude]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 12:34:36 GMT</pubDate>
            <atom:updated>2026-04-04T12:34:36.346Z</atom:updated>
            <content:encoded><![CDATA[<p>In a world full of constant communication, true emotional safety has become rare. Yet, it is the foundation of every strong relationship.</p><p>This book is not about becoming perfect. It is about choosing progress — every single day.</p><p>Through relatable life experiences and practical reflections, the author explores how mindset, emotional balance, love languages, and self-awareness shape the way we connect with others. You will discover why growth matters more than ego, why listening is more powerful than advising, and how small daily improvements can transform your relationships.</p><p>This is not just a book for couples. It is for friends, siblings, colleagues, and anyone who wants to build deeper trust and meaningful bonds.</p><p>If you want to grow into someone people naturally respect, trust, and feel comfortable opening up to — this book offers simple, real, and actionable insights to begin that journey.</p><p>Because the real question is not who makes you feel safe…<br>It is whether you are someone others feel safe with.</p><p>Resources:</p><p>🔗 Amazon: <a href="https://www.amazon.in/Are-Someone-Others-Feel-Safe/dp/B0GSV4843W">https://www.amazon.in/Are-Someone-Others-Feel-Safe/dp/B0GSV4843W</a><br>🔗 Flipkart: <a href="https://www.flipkart.com/you-someone-others-feel-safe-with/p/itm27b288836872c">https://www.flipkart.com/you-someone-others-feel-safe-with/p/itm27b288836872c</a><br>🔗 Notion: <a href="https://notionpress.com/in/read/are-you-someone-others-feel-safe-with">https://notionpress.com/in/read/are-you-someone-others-feel-safe-with</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*N33H3djzmfP4uw5lhseP6Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=245aa216bf2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable In-House Tool for Streamlining Database Audits]]></title>
            <link>https://engineering.bharatpe.com/scalable-in-house-tool-for-streamlining-database-audits-0cf4ec93edef?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cf4ec93edef</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[scalable]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[auditing]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 10:59:17 GMT</pubDate>
            <atom:updated>2025-02-21T10:59:17.045Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Ensuring Data Integrity: A System for Auditing What, Who, and When in Your Database</strong></p><p>Have you ever wondered <strong>who</strong> made changes to your database and <strong>when</strong>?</p><p>Or how to ensure every update was properly <strong>tracked</strong> and <strong>auditable</strong>?</p><p>In industries dealing with sensitive data, such as monetary transactions, maintaining this audit trail is crucial to maintaining trust.</p><p>At <a href="https://zillionrewards.in/">Zillion</a>, while re-architecting our Loyalty Management System (LMS), we faced the same challenge. We needed a system that could track critical changes across members, partners, and transactions, all while ensuring data integrity and compliance. The question was: How could we implement robust auditing without compromising on efficiency?</p><p>After exploring options like Apache Log4j, database triggers, and Javers, we found <a href="https://docs.spring.io/spring-data/envers/docs/current/reference/html/">Envers</a> to be the most effective solution. It allowed us to quickly integrate <strong>automatic versioning and auditing</strong> into our Hibernate-based system, ensuring detailed tracking with minimal changes to our code. Envers provided the scalability and simplicity we needed to monitor and manage every critical update, keeping our database operations secure and transparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Amqhg0bNWm2Q6VWNIUyNaQ.png" /></figure><p>However, as our system scaled, we began to encounter <strong>limitations</strong> with Envers that affected its effectiveness. Some of the challenges we faced with Envers include:</p><ul><li><strong>Scalability Bottleneck:</strong> Envers uses a single table named revInfo to manage revision IDs along with timestamps and other details (such as roles and emails) for all audit tables. This centralization creates a bottleneck, affecting scalability.</li><li><strong>Performance Issues:</strong> When multiple records are updated in a single request, the time required to update the main tables, their corresponding audit tables, and the revInfo table can result in API timeouts. The synchronous nature of these operations increases lock contention, as the database locks both the main and audit tables, resulting in slower response times.</li><li><strong>Inadequate Handling of Updates:</strong> The current implementation of Envers does not properly manage the creation of new revisions for UPDATE queries, leading to incomplete auditing of changes.</li><li><strong>Limited Control and Flexibility:</strong> Customizing and making changes to the existing implementation is quite challenging, limiting our ability to adapt the system to evolving needs.</li></ul><p>To overcome the limitations of Envers, we developed a tailored in-house solution that leveraged Aspect-Oriented Programming (AOP) to manage Spring and custom repository operations, employed Kafka for asynchronous processing, and made decisions on which tables needed updates. Additionally, we modified existing queries to fetch data from specialized audit and revision tables. By integrating these technologies, we have created a robust and scalable auditing system that effectively addresses our needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVCVsPfvkNGVQzt0fh19LA.png" /><figcaption>In house Audit System</figcaption></figure><p><strong>Here’s a high-level overview of our solution:</strong></p><ol><li><strong>Aspect-Oriented Programming (AOP):</strong></li></ol><p><strong>Pointcuts and Aspects:</strong> We created pointcuts to handle:</p><ul><li><strong>Spring Repository Operations:</strong> Any method with names starting with save* in Spring repositories triggers a pointcut on the afterReturning aspect, combined with entities annotated with a custom @Audit annotation.</li><li><strong>Custom Repositories:</strong> Any repository with native queries containing UPDATE operations ensures revisions are maintained.</li></ul><p>2. <strong>Asynchronous Processing with Kafka:</strong></p><ul><li><strong>Event Handling:</strong> Changes are pushed to Kafka to handle processing asynchronously.</li><li><strong>Revision History:</strong> Determine whether revision history needs to be maintained for each role interacting with the database.</li><li><strong>Audit and Revision Data:</strong> Decide which _audit tables and _revision_info records need to be updated.</li><li><strong>Database Updates:</strong> Update the MySQL _audit and _revision_info tables accordingly.</li></ul><p>3. <strong>Enhanced Query Handling:</strong></p><ul><li><strong>Specialized Tables:</strong> Modify existing queries to fetch data from specialized audit and revision tables (_audit and _revision_info).</li></ul><p>This solution addresses the scalability and performance issues previously faced and provides more control and flexibility in managing database changes.</p><p><strong>Step-by-Step Solution for Database Auditing</strong></p><ol><li><strong>Create an Audit Annotation:</strong></li></ol><p>Define a custom annotation named @Audit to mark entities that require auditing.</p><pre>@Retention(RetentionPolicy.RUNTIME)<br>@Target({ElementType.TYPE, ElementType.METHOD})<br>public @interface Audit {<br>}</pre><p>2. <strong>Annotate Entity Classes:</strong></p><p>Apply the @Audit annotation to your entity classes that you want to monitor for changes.</p><pre>@Entity<br>@Table(name = &quot;entity_table&quot;)<br>@Audit<br>public class EntityTable {<br>}</pre><p>3. <strong>Create an Aspect Class:</strong></p><p>Define an AuditAspect class to handle auditing logic using Aspect-Oriented Programming (AOP).</p><pre>@Slf4j<br>@Aspect<br>@Component<br>public class AuditAspect {<br><br>    private Map&lt;String, Integer&gt; revisionTypeMap;<br><br>    @PostConstruct<br>    public void init() {<br>        revisionTypeMap = new HashMap&lt;&gt;();<br>        revisionTypeMap.put(RevisionType.CREATED.name(), 0);<br>        revisionTypeMap.put(RevisionType.UPDATED.name(), 1);<br>        revisionTypeMap.put(RevisionType.DELETED.name(), 2);<br>    }<br>}</pre><p>4. <strong>Add Pointcuts in the Aspect Class:</strong></p><p>Create pointcuts to capture specific method executions related to entity operations.</p><pre>@Pointcut(&quot;execution(* org.springframework.data.repository.CrudRepository.save*(..))&quot;)<br>public void saveExecutionPointCut() {<br>}<br><br>@Pointcut(&quot;@annotation(org.springframework.data.jpa.repository.Query)&quot;)<br>public void queryPointCut() {<br>}</pre><p>5. <strong>Add Advices in the Aspect Class:</strong></p><p>Implement advice methods to handle the operations defined by your pointcuts.</p><pre>@AfterReturning(pointcut = &quot;saveExecutionPointCut()&quot;, returning = &quot;entity&quot;)<br>public void afterReturningSaveExecutionPointCut(Object entity) {<br><br>    if (Objects.nonNull(entity)) {<br>        List&lt;?&gt; entityList = (entity instanceof List) ? (List&lt;?&gt;) entity : List.of(entity);<br>        Class&lt;?&gt; clazz = entityList.get(0).getClass();<br><br>        boolean isAuditAnnotationPresent = clazz.isAnnotationPresent(Audit.class);<br>        <br>        if (isAuditAnnotationPresent) {<br>            if (TransactionSynchronizationManager.isSynchronizationActive()) {<br>                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {<br>                    @Override<br>                    public void afterCommit() {<br>                        handleAfterCommit(entityList, clazz);<br>                    }<br>                });<br>            } else {<br>                handleAfterCommit(entityList, clazz);<br>            }<br>        }<br>    }<br>}</pre><p>6. <strong>Send Data to Kafka Queue:</strong></p><p>Implement logic to send entity details and other related information to a Kafka queue for asynchronous processing.</p><pre>public void handleAfterCommit(List&lt;?&gt; entityList, Class&lt;?&gt; clazz) {<br>    Map&lt;String, Object&gt; message = new HashMap&lt;&gt;();<br>    populateTokenDetails(message);<br><br>    List&lt;Map&lt;String, Object&gt;&gt; entityMapList = populateEntityMapList(entityList, clazz);<br><br>    message.put(LmsConstants.Audit.ENTITY, entityMapList);<br>    message.put(LmsConstants.Audit.CLASS, clazz);<br><br>    log.info(&quot;Sending message: {} to notifyAuditTopic&quot;, message);<br>    kafkaProducer.sendMessage(notifyAuditTopic, message);<br>}</pre><p>7. <strong>Kafka Consumer Setup:</strong></p><p>Define a Kafka listener to consume messages from the specified topic. This listener processes the incoming messages and manages the acknowledgment of message processing.</p><pre>@KafkaListener(id = &quot;${audit.consumer.id}&quot;, topics = &quot;${audit.client.credential.topic}&quot;, groupId = &quot;${audit.groupId}&quot;)<br>public void auditClientCred(@Payload String message, Acknowledgment acknowledgment) {<br><br>    log.info(&quot;Inside AuditConsumer - {}&quot;, message);<br><br>    try {<br>        // Parse message to a Map<br>        Map&lt;String, Object&gt; messageMap = ParserUtil.parse(message, Map.class);<br><br>        // Extract class name and convert to Class object<br>        String clazzName = (String) messageMap.get(LmsConstants.Audit.CLASS);<br>        Class&lt;?&gt; clazz = Class.forName(clazzName);<br><br>        // Retrieve table name from the class annotation<br>        Table tableAnnotation = (Table) clazz.getAnnotation(Table.class);<br>        String tableName = tableAnnotation.name();<br><br>        // Extract entity list from the message<br>        List&lt;Map&lt;String, Object&gt;&gt; entityList = (List&lt;Map&lt;String, Object&gt;&gt;) messageMap.getOrDefault(LmsConstants.Audit.ENTITY, null);<br><br>        // Process each record if the list is not empty<br>        if (CollectionUtils.isNotEmpty(entityList)) {<br>            for (Map&lt;String, Object&gt; object : entityList) {<br>                saveRecordInAudit(object, tableName, messageMap);<br>            }<br>        }<br>        // Acknowledge message after processing<br>        acknowledgment.acknowledge();<br><br>    } catch (Exception ex) {<br>        log.error(&quot;AuditConsumer - Exception occurred while parsing message: {}&quot;, ex.getMessage());<br>    }<br>}</pre><p>8. <strong>Save Record in Audit Tables:</strong></p><p>Define a method to save the audit records into the database. This method manages transactions and ensures data integrity.</p><pre>public void saveRecordInAudit(Map&lt;String, Object&gt; records, String tableName, Map&lt;String, Object&gt; messageMap) {<br><br>    log.info(&quot;AuditConsumer - saveRecord&quot;);<br>    Session session = null;<br>    Transaction transaction = null;<br><br>    try {<br>        // Start a new session and transaction<br>        session = sessionFactory.openSession();<br>        transaction = session.beginTransaction();<br><br>        // Perform revision info operation and get the revision ID<br>        Long revisionId = performRevisionInfoOperation(messageMap, session, tableName);<br><br>        // Save audit record using the obtained revision ID<br>        performAuditOperation(revisionId, records, session, tableName);<br><br>        // Commit the transaction<br>        transaction.commit();<br><br>    } catch (Exception ex) {<br>        // Rollback transaction in case of an error<br>        if (transaction != null) {<br>            log.info(&quot;AuditConsumer - Rolling back transaction due to error: {}&quot;, ex.getMessage());<br>            transaction.rollback();<br>        }<br>        throw ex;<br>    } finally {<br>        // Close the session<br>        if (session != null) {<br>            session.close();<br>        }<br>    }<br>}</pre><p>9. <strong>Perform Revision Info Operation:</strong></p><p>Implement a method to insert revision details into the revision info table and retrieve the newly generated revision ID.</p><pre>private Long performRevisionInfoOperation(Map&lt;String, Object&gt; messageMap, Session session, String tableName) {<br><br>    // Extract email and role from the message map<br>    String email = (String) messageMap.getOrDefault(EMAIL, null);<br>    String role = (String) messageMap.getOrDefault(ROLE, null);<br><br>    // Define the revision info table name<br>    String auditRevisionInfo = tableName + auditRevisionInfoSuffix;<br>    log.info(&quot;auditRevisionInfo: {}&quot;, auditRevisionInfo);<br><br>    // Prepare and execute the insert query for revision info<br>    String revInfoQueryStatement = &quot;INSERT INTO &quot; + auditRevisionInfo + &quot; (email, role) VALUES (:value1, :value2)&quot;;<br>    Query revInfoQuery = session.createNativeQuery(revInfoQueryStatement);<br>    revInfoQuery.setParameter(&quot;value1&quot;, email);<br>    revInfoQuery.setParameter(&quot;value2&quot;, role);<br><br>    int rowsAffected = revInfoQuery.executeUpdate();<br>    if (rowsAffected &lt;= 0) {<br>        log.error(&quot;Insert query failed in rev info table&quot;);<br>        throw REV_INFO_OPERATION_FAILED;<br>    }<br><br>    // Retrieve the last inserted revision ID<br>    Query query = session.createNativeQuery(&quot;SELECT LAST_INSERT_ID(Id) FROM &quot; + auditRevisionInfo + &quot; ORDER BY LAST_INSERT_ID(Id) DESC LIMIT 1&quot;);<br>    Long revisionId = ((Number) query.getSingleResult()).longValue();<br><br>    return revisionId;<br>}</pre><p><strong>Conclusion</strong></p><p>Implementing this auditing solution provided several benefits to our system. By using Aspect-Oriented Programming with the custom @Audit annotation, we achieved a clean separation of auditing logic from business logic, reducing code clutter and enhancing maintainability. Integrating with Kafka allowed us to handle audit data asynchronously, improving system performance and scalability. Storing audit records in dedicated tables ensured a reliable and queryable history of changes. Overall, this approach streamlined our auditing processes, ensuring data integrity and accountability while minimizing the impact on system performance.</p><p>I hope you enjoy it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cf4ec93edef" width="1" height="1" alt=""><hr><p><a href="https://engineering.bharatpe.com/scalable-in-house-tool-for-streamlining-database-audits-0cf4ec93edef">Scalable In-House Tool for Streamlining Database Audits</a> was originally published in <a href="https://engineering.bharatpe.com/">BharatPe Tech Chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FIFO in Database Handling]]></title>
            <link>https://medium.com/@sahilbajaj85/fifo-in-database-handling-786ce96b6bf5?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/786ce96b6bf5</guid>
            <category><![CDATA[fifo]]></category>
            <category><![CDATA[first-in-first-out]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 16:54:39 GMT</pubDate>
            <atom:updated>2025-02-10T16:54:39.743Z</atom:updated>
            <content:encoded><![CDATA[<p>When you hear the word FIFO, what comes to your mind?</p><p>For many programmers, it instantly brings the vision of a <strong>queue</strong>. And that’s exactly right! FIFO stands for <strong>First In, First Out</strong>, meaning the first item to enter the system is the first to leave. It’s a simple yet powerful concept widely used in programming, especially when managing data in an orderly fashion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6_-debO0w7CGuf-39zBDQ.jpeg" /></figure><p>During our graduation, most of us had hands-on experience with FIFO, especially when working with queues. But have you ever considered how to apply this concept when dealing with database records?</p><p>A naive approach might be fetching all records for a user based on the created date, filtering out the relevant ones, and moving forward with your main logic. Simple, right?</p><p>Yes, it’s straightforward, but not exactly scalable. When this needs to be done for multiple users, the cost increases significantly. Fetching, filtering, and processing large datasets for each user becomes inefficient, leading to slower performance and increased resource usage. This is where a more optimised approach is crucial for handling FIFO with database records efficiently.</p><p>What if, instead of fetching all records for a user, we only retrieve the ones that are actually useful to us? It sounds more efficient, right? But how can we achieve this?</p><p>To make this work, we need to apply query-level logic to decide which records should be fetched. It’s all about shifting the logic to the query level for better scalability and efficiency.</p><p>Let’s consider a scenario: Imagine you need to fetch a set of records to deduct stocks being sold against those that were bought, following a FIFO (First-In, First-Out) approach.</p><p>To achieve this, you need to select only those records where the total stock equals or just exceeds the required value, while ensuring the records remain sorted by their creation date. By fetching the data in a sorted order, we inherently ensure that we are processing the records in a <strong>FIFO</strong> manner — the first records to come in are processed first.</p><p>This approach brings two key benefits:</p><ol><li><strong>FIFO Integrity</strong>: Sorting the records by the creation date ensures that the oldest records are prioritised, which aligns with the FIFO concept.</li><li><strong>Optimised Data Handling</strong>: By limiting the number of records fetched, we focus only on the relevant data. This prevents unnecessary overhead and improves the efficiency of the operation, making it far more scalable and manageable as the number of users or records increases.</li></ol><p>In this way, we achieve both a FIFO order and optimised data handling, leading to more efficient performance while maintaining the desired logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqFbPdVbg0LvZv2C_q4zoA.png" /></figure><p>Wait, there’s still a catch. In the scenario we’ve discussed, if you notice, we only need 10 units out of the 40 from record 3. So, we should be able to utilize the remaining 30 units of that record in the next processing cycle, right?</p><p>There are two ways to achieve this.</p><ul><li>One approach is to add an extra column in the database to track the stocks that has been used. Each time a record is processed, we update this column with the stocks consumed, leaving the remaining balance available for future use.</li><li>Alternatively, we could set the initial stocks in the field and simply decrement it by the stocks that has been used. For example, if we start with 40 units and use 10, we subtract 10, leaving 30 for the next round of processing.</li></ul><p>By adopting the second approach, the query becomes simpler, as we can ignore records where the remaining stock becomes zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*6vNiLhByYter34GaQTjx6A.png" /></figure><p>Now, let’s dive into the main query logic.</p><pre>WITH IntermediateRecords AS <br>   (<br>      SELECT *, <br>      :sellStocks - SUM(remainingStocks) <br>      OVER (ORDER BY createdDate ASC) <br>      AS remaining_stocks_running<br>      FROM table <br>      WHERE userId = :userId AND remainingStocks &gt; 0<br>   )<br>SELECT * FROM IntermediateRecords <br>WHERE <br>remaining_stocks_running &gt;= 0 <br>OR <br>(remaining_stocks_running + remainingStocks) &gt;= 0</pre><p>Let’s break it down</p><pre>SELECT *, <br>      :sellStocks - SUM(remainingStocks) <br>      OVER (ORDER BY createdDate ASC) <br>      AS remaining_stocks_running<br>      FROM table <br>      WHERE userId = :userId AND remainingStocks &gt; 0</pre><p>In this scenario, userId represents the user&#39;s ID, and sellStocks refers to the stocks being sold. These values are passed as input. The goal is to fetch records where the userId matches and the remainingStocks have not yet reached zero. The query will then use ‘ORDER BY createdDate ASC’ to sort the filtered records in ascending order based on the creation date. While sorting the records, the query also calculates a temporary attribute, named remaining_stocks_running, which is the result of :sellStocks - cumulative sum of stocks from all previous records. This allows us to track how much stock remains to be sold as we process each record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*JN0KRsQlYYV3Yn9qfxlIRQ.png" /></figure><pre>SELECT * FROM IntermediateRecords <br>WHERE <br>remaining_stocks_running &gt;= 0 <br>OR <br>(remaining_stocks_running + remainingStocks) &gt;= 0</pre><p>If you observe the above photo, the useful records are those where remaining_stocks_running &gt;= 0, which includes Record 1 and Record 2. However, we also need to include Record 3. For this record, the condition (remaining_stocks_running + remainingStocks) &gt;= 0 must be satisfied, allowing us to consider it as part of the valid records.</p><p>Let’s take a closer look at the condition (remaining_stocks_running + remainingStocks) &gt;= 0:</p><ul><li><strong>Record 3</strong>: (remaining_stocks_running + remainingStocks) = -30 + 40 = 10 → This satisfies the condition, so Record 3 is valid.</li><li><strong>Record 4</strong>: (remaining_stocks_running + remainingStocks) = -60 + 30 = -30 → This does <strong>not</strong> satisfy the condition (since it’s less than 0), so Record 4 is not valid.</li><li><strong>Record 5</strong>: (remaining_stocks_running + remainingStocks) = -110 + 50 = -60 → This also does <strong>not</strong> satisfy the condition, so Record 5 is not valid either.</li></ul><p>Thus, the condition ensures that only records like Record 3, where the sum of the remaining_stocks_running and remainingStocks is non-negative, are considered valid.</p><h3>Conclusion</h3><p>In this approach, we sort transactions by createdDate in ascending order and calculate a temporary attribute, remaining_stocks_running, which tracks the cumulative stock count from previous records. The useful records are those where remaining_stocks_running &gt;= 0. Additionally, to include records like Record 3, we check the condition (remaining_stocks_running + remainingStocks) &gt;= 0. This ensures that only valid transactions, where stock remains to be deducted or partially sold, are considered for processing.</p><p><em>Thanks for reading. Hope you enjoyed it!!!</em></p><p><strong>More Related Articles</strong></p><p><a href="https://medium.com/@sahilbajaj85/less-code-more-impact-scalable-exception-handling-03d90e9766ec">Less Code, More Impact: Scalable Exception Handling</a></p><p><a href="https://medium.com/@sahilbajaj85/graceful-synchronisation-for-concurrent-traffic-07380380604e">Graceful Synchronisation for Concurrent Traffic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786ce96b6bf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Less Code, More Impact: Scalable Exception Handling]]></title>
            <link>https://medium.com/@sahilbajaj85/less-code-more-impact-scalable-exception-handling-03d90e9766ec?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d90e9766ec</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[learner]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 05:30:57 GMT</pubDate>
            <atom:updated>2024-12-18T05:30:57.911Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we frequently deal with situations that require handling different type of exceptions. These exceptions are communicated from the backend to the frontend to notify the user about issues, whether they are related to 4xx (client-side) or 5xx (server-side) errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*RBxqNJsYoboPap0iimGjKA.jpeg" /></figure><p>A simple way to achieve this is by doing something like:</p><pre>throw new RuntimeException(&quot;Something went wrong&quot;);</pre><pre>return new ResponseEntity<br>              .status(HttpStatus.BAD_REQUEST)<br>              .body(new ApiResponse&lt;&gt;(&quot;Invalid Input&quot;));</pre><p>It works, right? After all, this is what we’ve learned during our graduation. However, this solution quickly becomes unmanageable as multiple developers work on the same project. Without a defined standard for choosing the appropriate HTTP status based on the type of exception, most of us default to using HttpStatus.BAD_REQUEST or HttpStatus.INTERNAL_SERVER_ERROR.</p><blockquote><strong>Use of Custom Exceptions via RestControllerAdvice</strong></blockquote><p>To establish a standard for handling HTTP status code in exceptions, we can introduce custom exceptions in our code, such as ConflictException, BadRequestException, DataNotFoundException, and implement @RestControllerAdvice accordingly.</p><pre>// Custom Exception Example<br>public class BadRequestException extends RuntimeException {<br>    public BadRequestException(String message) {<br>        super(message);<br>    }<br>}</pre><pre>throw new BadRequestException(&quot;Invalid request&quot;);</pre><pre>// @RestControllerAdvice for centralized exception handling<br>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(BadRequestException.class)<br>    public ResponseEntity&lt;Object&gt; handleBadRequestException(BadRequestException ex) {<br>        return ResponseEntity<br>              .status(HttpStatus.BAD_REQUEST)<br>              .body(new ApiResponse&lt;&gt;(ex.getMessage()));<br>    }<br><br>    @ExceptionHandler(InternalServerErrorException.class)<br>    public ResponseEntity&lt;Object&gt; handleInternalServerErrorException(InternalServerErrorException ex) {<br>        return ResponseEntity<br>              .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>              .body(new ApiResponse&lt;&gt;(ex.getMessage()));        <br>    }<br>}</pre><p>This allows us to better manage error messages, make our code more maintainable, and ensure consistency in how HTTP statuses are assigned to different types of errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*9qqeZM5oAB-4oclGG-h1EQ.jpeg" /></figure><p><strong>Surprise time!</strong><br>In an agile development environment, new requirements often arise. What if we get one such requirement to limit the error messages shown to users, as displaying all backend errors may not always be meaningful or helpful. So, how can we implement this efficiently in our code?</p><blockquote><strong>Approach 1</strong>: Update exception message</blockquote><pre>return new ResponseEntity<br>              .status(HttpStatus.BAD_REQUEST)<br>              .body(new ApiResponse&lt;&gt;(&quot;New Error Msg&quot;));</pre><p>Although this solution seems to be very easy and direct, however making these changes through out the project can be cumbersome and inefficient.</p><blockquote><strong>Approach 2</strong>: Handle in RestControllerAdvice</blockquote><p>We may also think around having a local map, where we may convert backend thrown exception messages with what has to be shown to the frontend.</p><pre>// @RestControllerAdvice for centralized exception handling<br>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    private Map&lt;String, String&gt; exMap;<br><br>    @PostConstruct<br>    public void() {<br>      exMap = new HashMap&lt;&gt;();<br>      exMap.put(&quot;Invalid request&quot;, &quot;New Error Msg&quot;);<br>    }<br><br>    @ExceptionHandler(BadRequestException.class)<br>    public ResponseEntity&lt;Object&gt; handleBadRequestException(BadRequestException ex) {<br>        return ResponseEntity<br>              .status(HttpStatus.BAD_REQUEST)<br>              .body(new ApiResponse&lt;&gt;(exMap.get(ex.getMessage())));<br>    }<br><br>    @ExceptionHandler(InternalServerErrorException.class)<br>    public ResponseEntity&lt;Object&gt; handleInternalServerErrorException(InternalServerErrorException ex) {<br>        return ResponseEntity<br>              .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>              .body(new ApiResponse&lt;&gt;(exMap.get(ex.getMessage())));        <br>    }<br>}</pre><p>However, above approach has following limitations:</p><ul><li>This will convert exception messages for all the products under current project. What if we want to show different messages for one product and other for another product, under InternalServerErrorException. This will require to pass HttpServletRequest, from which based on request url, product can be derived and correspondingly associated error message.</li><li>Above change will require changes in all ExceptionHandler methods</li><li>Tight coupling and complexity of code</li><li>What if product requirement is to have different default messages against each flow / api’s</li></ul><blockquote><strong>Final Approach</strong>: Leverage Interceptors for Effective Exception Handling</blockquote><pre>public interface CustomisedException {<br><br>    String getCustomisedMsg(String msg, String url, String type);<br>}</pre><pre>@Service<br>public class Product1CustomisedException implements CustomisedException {<br><br>    private Map&lt;String, String&gt; flow1ExceptionMap;<br>    private Map&lt;String, String&gt; flow2ExceptionMap;<br>    ...<br><br><br>    @PostConstruct<br>    void init() {<br>        flow1ExceptionMap = new HashMap&lt;&gt;();<br><br>        flow2ExceptionMap = new HashMap&lt;&gt;();<br>        flow2ExceptionMap.put(“ACCOUNT_ALREADY_EXISTS”, Constants.PRODUCT1_EXCEPTION_MSG_UI.REACH_SUPPORT_TEAM);<br>        flow2ExceptionMap.put(“KYC_REJECTED”, Constants.PRODUCT1_EXCEPTION_MSG_UI.REACH_SUPPORT_TEAM);<br>        flow2ExceptionMap.put(“KYC_NOT_INITIATED”, Constants.PRODUCT1_EXCEPTION_MSG_UI.REACH_SUPPORT_TEAM);<br><br>        ...<br>    }<br><br>    @Override<br>    public String getCustomisedMsg(String msg, String url, String type) {<br><br>        Product1RequestIdentifierEnum key = getKey(url, type);<br>        if (Objects.nonNull(key)) {<br>            switch (key) {<br>                case FLOW1:<br>                    return flow1ExceptionMap.getOrDefault(msg, Constants.PRODUCT1_EXCEPTION_MSG_UI.BACK_BUTTON_TRY_AGAIN);<br>                case FLOW2:<br>                    return flow2ExceptionMap.getOrDefault(msg, Constants.PRODUCT1_EXCEPTION_MSG_UI.BACK_BUTTON_TRY_AGAIN);<br>                ...<br>                <br>                default:<br>                    log.warn(&quot;Customised Mapping not done for url: {}, type: {}&quot;, url, type);<br>            }<br>        }<br>        return msg;<br>    }<br><br>    private Product1RequestIdentifierEnum getKey(String url, String type) {<br><br>        switch (type) {<br>            case &quot;GET&quot;:<br>                switch (url) {<br>                    case Constants.URL1<br>                        return FLOW1;<br>                }<br>                break;<br>            case &quot;POST&quot;:<br>                switch (url) {<br>                    case Constants.URL2:<br>                        return FLOW2;<br>                }<br>                break;<br>            default:<br>                log.warn(&quot;Unknown request type received: {}&quot;, type);<br>        }<br>        return null;<br>    }<br>}</pre><pre>@Component<br>public class CustomisedExceptionFactory {<br><br>    @Autowired<br>    private CustomisedException product1CustomisedException;<br><br>    public CustomisedException getCustomisedException(String key) {<br><br>        if (StringUtils.isBlank(key))<br>            return null;<br><br>        switch (key) {<br>            case &quot;product1&quot;:<br>                return product1CustomisedException;<br>            default:<br>                return null;<br>        }<br>    }<br><br>}</pre><pre>@Component<br>public class CustomisedExceptionInterceptor implements HandlerInterceptor {<br><br>    @Autowired<br>    private CustomisedExceptionFactory customisedExceptionFactory;<br>    @Autowired<br>    private ObjectMapper objectMapper;<br><br>    @Override<br>    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {<br><br>        if (Objects.nonNull(ex) || isExceptionStatus(response.getStatus())) {<br>            String key = getKey(request.getRequestURI());<br>            CustomisedException customisedException = customisedExceptionFactory.getCustomisedException(key);<br>            if (Objects.nonNull(ex)) {<br>                if (Objects.isNull(customisedException)) {<br>                    throw ex;<br>                }<br>                String exMsg = customisedException.getCustomisedMsg(ex.getMessage(), request.getRequestURI(), request.getMethod());<br>                throw new CustomException(exMsg);<br>            } else {<br>                if (Objects.nonNull(customisedException)) {<br>                    ContentCachingResponseWrapper cachingResponse = (ContentCachingResponseWrapper) response;<br>                    String responseBody = new String(cachingResponse.getContentAsByteArray(), StandardCharsets.UTF_8);<br>                    JsonNode jsonNode = objectMapper.readTree(responseBody);<br>                    String exceptionMessage = jsonNode.path(&quot;message&quot;).asText();<br>                    if (StringUtils.isNotEmpty(exceptionMessage)) {<br>                        String exMsg = customisedException.getCustomisedMsg(exceptionMessage, request.getRequestURI(), request.getMethod());<br>                        responseBody = responseBody.replaceAll(exceptionMessage, exMsg);<br>                    }<br>                    int status = response.getStatus();<br>                    String contentType = response.getContentType();<br>                    /** <br>                      Tricky Logic - Cleared earlier response, <br>                                     Set with status, contentType &amp; responseBody<br>                                     And Commited the response by flushing<br>                    **/<br>                    response.reset();<br>                    cachingResponse.setStatus(status);<br>                    cachingResponse.setContentType(contentType);<br>                    response.getWriter().write(responseBody);<br>                    response.flushBuffer();<br>                }<br>            }<br>        }<br>    }<br><br>    private String getKey(final String requestURI) {<br><br>        if (requestURI.contains(&quot;/product1&quot;)) {<br>            return &quot;product1&quot;;<br>        }<br><br>        return null;<br>    }<br><br>    private boolean isExceptionStatus(int status) {<br>        return (status &gt;= 300);<br>    }</pre><h3>Conclusion</h3><p>Based on product requirement, there can be multiple ways to achieve the same. However knowing various approaches help to decide the better solution for the problem in hand.</p><p><em>Thanks for reading. Hope you enjoyed it!!!</em></p><p><strong>More Related Articles</strong></p><p><a href="https://medium.com/@sahilbajaj85/graceful-synchronisation-for-concurrent-traffic-07380380604e">Graceful Synchronisation for Concurrent Traffic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d90e9766ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graceful Synchronisation for Concurrent Traffic]]></title>
            <link>https://medium.com/@sahilbajaj85/graceful-synchronisation-for-concurrent-traffic-07380380604e?source=rss-b92473f53244------2</link>
            <guid isPermaLink="false">https://medium.com/p/07380380604e</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[observer-design-pattern]]></category>
            <category><![CDATA[scalable]]></category>
            <dc:creator><![CDATA[Sahil Bajaj]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 17:03:07 GMT</pubDate>
            <atom:updated>2024-12-18T05:32:14.081Z</atom:updated>
            <content:encoded><![CDATA[<p>What haunts a developer every night are the concurrency issues that may arise from the code they’ve written. We always strive to write bug-free code and thoroughly test it on our local systems. However, our QA (Quality Assurance) teams often still find bugs in our features. Even worse, there are many cases that slip past the QA process and eventually make their way into the production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*WQwQVPYQQe_NdIm__iDL-g.jpeg" /></figure><p>Dealing with concurrency is not straightforward. It can arise at various levels, such as the database, downstream integrations, or even the code we write. There are multiple mechanisms to address different types of concurrency at each of these levels. The scope of this post will be limited to concurrency issues at the API level.</p><h3><strong>Background</strong></h3><p>I was working on a feature that allow users to buy gold from our platform. This requires an API with the following steps:</p><ol><li>Acquire a lock on the user ID</li><li>Validate the user request</li><li>Create an entry in our table</li><li>Perform request sanitisation along downstream</li><li>Return the payment gateway deep link</li><li>Release the lock</li></ol><p>The deep link contains a unique order ID for each transaction. Our app then opens the deep link, allowing the user to complete the payment.</p><h3><strong>Problem Statement</strong></h3><p>If we receive buy request for the same user while another buy transaction is already in progress, we fail to acquire the lock and throw an exception to the app, indicating that the transaction could not be processed. As a result, when the app receives the exception, the user is unable to process the successful deep link response. This leads to the user seeing an error, making it appear as though something went wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*aH9JvQx8H-bwrZ9zmYwOVQ.jpeg" /></figure><h3>Analysis &amp; Experiments</h3><ul><li>This issue is not affecting all users, but only new users who are being onboarded during the same transaction.</li><li>It’s not only impacting customer experience but also leading to business loss, as many users do not return to try investing again.</li><li>Although all APIs (KYC check, user registration, acceptance of agreement, and gold purchase) were made transactional within the app, and the button was disabled until all APIs were completed, two calls are still being received at the backend for the same user within milliseconds.</li><li>We attempted to make the “Gold Purchase” API transactional as well within the app, but unfortunately, we were still unsuccessful.</li></ul><h3>Goals</h3><p>Provide a good experience for customers and reduce the impact of business losses.</p><h3>Solution</h3><blockquote><strong><em>Approach 1</em></strong><em>: Exploring the Observer Design Pattern</em></blockquote><pre>class LockResponse {<br><br>  // This is to copy parent response to child response, <br>  // so that child transactions have access to the data<br>  Object response;<br>  // This reference is required so as we can interupt child transaction, <br>  // once parent response is ready<br>  Thread currentThread;<br>}</pre><pre>class ObserverService {<br><br>   // Initialise them <br>   Map&lt;String, LockResponse&gt; parentTxnMap;<br>   Map&lt;String, LockResponse&gt; childTxnMap;<br><br>   void subsribe(String key, LockResponse response) {<br>      /**<br>         Checks if parentTxnMap contains key<br>             Fetch list of child transactions from childTxnMap. Default to empty linkedList<br>             Add response to child transaction list<br>             Save back the list in childTxnMap under same key<br>        Else<br>            Add response in parentTxnMap<br>      **/<br>   }<br><br>   void unsubscribe(String key, Object response) {<br>     // Remove key from parentTxnMap<br>     // Notify Subscribers with response against key<br>   }<br><br>   void notifySubscribers(String key, Object response) {<br>     /**<br>        Fetch child transactions list from childTxnMap based key<br>        if list is not empty<br>            For each entity in list <br>                Set parent response in child LockResponse<br>                Interupt child thread<br>        Remove key from childTxnMap<br>     **/<br>   }<br>}</pre><pre>void buyGold(String userId) {<br><br>  LockResponse lockResponse = new LockResponse();<br>  try {<br><br>      // Acquire Lock<br><br>      lockResponse.setCurrentThread(Thread.currentThread());<br>      observerService.subsribe(ownerId, lockResponse);<br>      <br>      /**<br>        Validate the user request<br>        Create an entry in our table<br>        Perform request sanitisation along downstream<br>        String deepLink = Return the payment gateway deep link<br>      **/<br><br>      observerService.unsubsribe(ownerId);<br>      return deepLink;<br><br>    // This exception will be thrown if acquire lock fails.<br>  } catch (LockException ex) {<br>     <br>      try {<br>        lockResponse.setCurrentThread(Thread.currentThread());<br>        observerService.subsribe(ownerId, lockResponse);<br>        /**<br>          Sleep thread for next 500 milli second. <br>          Average TAT of this api is ~250ms<br>          So, when the response is ready, this thread is interupted.<br>        **/<br>        Thread.sleep(500);<br><br>      } catch (InterupptedException ex) {<br>        <br>          if (lockResponse.getResponse() != null) {<br>            // This is the parent response, being returned by child transaction<br>            return lockResponse.getResponse();<br>          }<br>          // Default fallback, if lockResponse.getResponse is not populated<br>          throw new Exception();<br>      }<br>  }<br><br>} </pre><p><em>Wowww!!! Solution looks great. But there is an issue. This is not scalable to multiple POD’s / Servers</em></p><blockquote><strong>Approach 2</strong>: Make use of Redis (Cache) to handle multiple POD’s / Servers</blockquote><pre>void subsribe(String key, LockResponse response) {<br>      /**<br>         Object parentValue = Fetch value from redis against parent txn key<br>         Checks if parentValue is nonNull<br>             Object childValue = Fetch list of child transactions from redis under child key.<br>             Add response to child transaction list<br>             Save back the list in redis under same child key<br>        Else<br>            Add response in redis against parent txn key with some expiry<br>      **/<br>   }<br><br>   void unsubscribe(String key, Object response) {<br>     // Remove key from redis against parent txn key<br>     // Notify Subscribers with response against key<br>   }<br><br>   void notifySubscribers(String key, Object response) {<br>     /**<br>        Fetch child transactions list from redis based child key<br>        if list is not empty<br>            For each entity in list <br>                Set parent response in child LockResponse<br>                Interupt child thread<br>        Remove key from redis for child key<br>     **/<br>   }</pre><p><em>Nice !!! All sorted !! NO saving thread in redis caused circular dependency issue while serialisation and de-serialisation</em></p><blockquote><strong>Final Approach</strong>: Default down to thread sleep timeout</blockquote><p>Now, we have to keep moving, and achieve our goal, one way or the other. How about making use of auto thread wake up after x milli seconds of time (this will be slightly higher than average api response time), so as when child transaction wakes up, parent transaction should be ready with the response</p><pre>Delete class LockResponse. <br>Its not required now, as we do not require to save child thread reference</pre><pre><br>  /**<br>    Values are saved in redis against parent and child key, <br>    PARENT_TXN + key - If there is any existing transaction <br>          which is inprogress<br>    CHILD_TXN + key - If there is any child transaction <br>          which needs to be notified<br><br>    LockResponse response - Removed. No more needed<br>  **/<br>   void subsribe(String key) {<br><br>      Object parentValue = redisService.getValue(PARENT_TXN + key);<br>      if (Objects.nonNull(parentValue)) {<br>          Object childValue = redisService.getValue(CHILD_TXN + key);<br>          if (Objects.isNull(childValue)) {<br>             redisService.setValue(CHILD_TXN + key, TIMEOUT, &quot;{any random value}&quot;);<br>          }<br>      } else {<br>          redisService.setValue(PARENT_TXN + key, TIMEOUT, key);<br>      }<br>   }<br><br>   /** <br>        To free up parent key from redis, <br>              once transaction is complete and response is ready to be returned<br><br>        response - This is the deep link response parent transaction is <br>              supposed to return to the app<br>   **/<br>   void unsubscribe(String key, Object response) {<br>     <br>      redisService.removeKey(PARENT_TXN + key);<br>      notifySubscribers(key, response);<br>   }<br><br>   void notifySubscribers(String key, Object response) {<br>     <br>      Object childValue = redisService.getValue(CHILD_TXN + key);<br>      if (Objects.nonNull(childValue)) {<br>          Object res = new Object();<br>          /** <br>              Copy response into res, <br>              as response reference may get freed <br>              once parent transaction is finished.<br><br>              Save serialised res against child transaction key in redis<br>        **/<br>        redisService.setValue(CHILD_TXN + key, <br>            objectMapper.writeValueAsString(res))<br>      }<br><br><br>      // This is new method which is required to fetch child response<br>      Object fetchResponse(String key) {<br>        <br>          Object finalRes = null;<br>          Object childValue = redisService.getValue(CHILD_TXN + key);<br>          /** <br>              This is to ensure <br>              child value is neither null(means key exists in redis) and<br>              nor default value - {any random value} <br>                  (means value has been updated by parent transaction)<br>          **/<br>          if (Objects.nonNull(childValue) &amp;&amp; <br>            !{any random value}.equals(childValue)) {<br>              finalRes = objectMapper.readValue((String)childValue, <br>                  new TypeReference&lt;Object&gt;() {})<br>          }<br>          redisService.removeKey(CHILD_TXN + key);<br>          return finalRes;<br>      }<br>   }</pre><pre>void buyGold(String userId) {<br><br>   // --------  No more needed -------<br>   // LockResponse lockResponse = new LockResponse();<br>  try {<br><br>      // Acquire Lock<br><br>      // --------  No more needed -------<br>      // lockResponse.setCurrentThread(Thread.currentThread());<br>      <br>       observerService.subsribe(ownerId);<br>      <br>      /**<br>        Validate the user request<br>        Create an entry in our table<br>        Perform request sanitisation along downstream<br>        String deepLink = Return the payment gateway deep link<br>      **/<br><br>      observerService.unsubsribe(ownerId);<br>      return deepLink;<br><br>    // This exception will be thrown if acquire lock fails.<br>  } catch (LockException ex) {<br>     <br>      try {<br>        // --------  No more needed -------<br>        // lockResponse.setCurrentThread(Thread.currentThread());<br>        <br>        observerService.subsribe(ownerId);<br>        /**<br>          Sleep thread for next 500 milli second. Considering some buffer time<br>          Average TAT of this api is ~250ms<br>          So, when the response is ready, this thread is interupted.<br>        **/<br>        Thread.sleep(500);<br><br>        Object res = observerService.fetchResponse(ownerId);<br>        if (res != null) {<br>            return res;<br>        }<br>        // Default fallback, if lockResponse.getResponse is not populated<br>        throw new Exception();<br><br>      } <br>  }<br><br>}</pre><p><em>Isn’t it cool !!! Yeah !! This solution works well for 1 parent and 1 child transaction, along assumption that child transaction will not take more than average api response time.</em></p><blockquote>Improvisation: Storing count of child transactions awaiting processing</blockquote><p>So, we require to store redis value, as number of child transaction waiting, against child transaction key, during subscribe. And decrease this count during fetchResponse api untill count reaches to 0, post which we should remove child response from redis.</p><h3>Conclusion</h3><p>There could have been better approach to this. However this is one of the possible approach I took to solve the problem in hand. And rather than just leaving things on luck, solved 92% of customer experience by this solution.</p><p><em>Thanks for reading. Hope you enjoyed it!!!</em></p><p><strong>More Related Articles</strong></p><p><a href="https://medium.com/@sahilbajaj85/less-code-more-impact-scalable-exception-handling-03d90e9766ec">Less Code, More Impact: Scalable Exception Handling</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07380380604e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>