<?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 Yashika Vijayvargiya on Medium]]></title>
        <description><![CDATA[Stories by Yashika Vijayvargiya on Medium]]></description>
        <link>https://medium.com/@yashika270499?source=rss-b5b68cc155e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2yRd1XqzOxDG-Q5ULxMF8g.jpeg</url>
            <title>Stories by Yashika Vijayvargiya on Medium</title>
            <link>https://medium.com/@yashika270499?source=rss-b5b68cc155e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:08:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashika270499/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[Rate Limiting in Rails 8.1: Protect Your APIs Without Rack::Attack]]></title>
            <link>https://medium.com/@yashika270499/rate-limiting-in-rails-8-1-protect-your-apis-without-rack-attack-e8f17e808416?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f17e808416</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 10:41:02 GMT</pubDate>
            <atom:updated>2026-11-02T10:41:02.241Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered what happens when someone sends hundreds of requests to your login endpoint within a few seconds?</p><p>Without rate limiting, your application could face unnecessary database queries, excessive server load, brute-force login attempts, or API abuse.</p><p>Rate limiting helps control how frequently a client can access an endpoint within a specified time window.</p><p>The good news is that Rails provides a built-in rate_limit method, so you don&#39;t always need an additional gem to implement basic rate limiting.</p><p><strong>Rails 8.1 also introduces a useful improvement: the</strong> scope: <strong>option, which allows multiple controllers to share the same rate-limit counter.</strong></p><p>Let’s understand how it works with practical examples.</p><h3>1. What Is Rate Limiting?</h3><p>Rate limiting is a technique used to restrict the number of requests a client can make within a specific period.</p><p>For example:</p><ul><li>Allow 5 login attempts within 3 minutes.</li><li>Allow 100 API requests per minute.</li><li>Allow 10 password reset requests within 15 minutes.</li></ul><p>When a client exceeds the configured limit, the application rejects additional requests.</p><p>Usually, the server responds with:</p><pre>HTTP 429 Too Many Requests</pre><p>This helps protect application resources and reduces abuse.</p><h3>2. Rails Built-in Rate Limiting</h3><p>Rails provides the rate_limit class method in Action Controller.</p><p>You can configure it directly inside a controller without installing an additional gem.</p><p>Let’s consider a login endpoint.</p><pre># app/controllers/sessions_controller.rb</pre><pre>class SessionsController &lt; ApplicationController<br>  rate_limit to: 5, within: 3.minutes, only: :create</pre><pre>  def create<br>    # Login authentication logic<br>  end<br>end</pre><p>Let’s understand the configuration:</p><p>Option</p><p>Meaning</p><p>to: 5</p><p>Maximum 5 requests</p><p>within: 3.minutes</p><p>Within a 3-minute window</p><p>only: :create</p><p>Apply the limit only to the create action</p><p>By default, Rails identifies requests using the client’s IP address.</p><p>When the limit is exceeded, Rails raises ActionController::TooManyRequests, which Action Dispatch handles by returning HTTP 429.</p><h3>3. Customize the Rate Limit Response</h3><p>The default response might not be sufficient for an API application.</p><p>You can customize the response using the with: option.</p><pre>class SessionsController &lt; ApplicationController<br>  rate_limit to: 5,<br>             within: 3.minutes,<br>             only: :create,<br>             with: -&gt; {<br>               render json: {<br>                 error: &quot;Too many login attempts. Please try again later.&quot;<br>               }, status: :too_many_requests<br>             }</pre><pre>  def create<br>    # Login authentication logic<br>  end<br>end</pre><p>Now, when a client exceeds the configured limit, the API returns a JSON error response.</p><p>Example:</p><pre>{<br>  &quot;error&quot;: &quot;Too many login attempts. Please try again later.&quot;<br>}</pre><p>With HTTP status:</p><pre>429 Too Many Requests</pre><p>This is particularly useful when building APIs consumed by React, mobile applications, or other external clients.</p><h3>4. Rate Limit Based on User Instead of IP</h3><p>By default, Rails applies rate limiting based on the request IP address.</p><p>But what if you want to apply limits per authenticated user?</p><p>You can customize the identifier using the by: option.</p><pre>class Api::BaseController &lt; ApplicationController<br>  rate_limit to: 100,<br>             within: 1.minute,<br>             by: -&gt; { current_user&amp;.id || request.remote_ip }<br>end</pre><p>Here:</p><ul><li>Authenticated users are identified by their user ID.</li><li>Unauthenticated requests are identified by their IP address.</li><li>Each identifier gets its own rate-limit counter.</li></ul><p>This is useful when you want to provide individual API limits to authenticated users.</p><p><strong>Important:</strong> If your application runs behind a proxy or load balancer, configure trusted proxy handling correctly. Otherwise, IP-based limits may not identify clients as expected.</p><h3>5. What’s New in Rails 8.1? The scope: Option</h3><p>This is one of the most useful improvements to the built-in rate-limiting functionality.</p><p>Before Rails 8.1, rate-limit counters were scoped to individual controller paths by default.</p><p>Consider an API application with two controllers:</p><pre>Api::PostsController<br>Api::UsersController</pre><p>Suppose both controllers have the following configuration:</p><pre>rate_limit to: 100, within: 1.minute</pre><p>By default, these controllers maintain separate counters.</p><p>This means a client could make:</p><ul><li>100 requests to the posts endpoint.</li><li>100 requests to the users endpoint.</li></ul><p>That’s 200 requests in total.</p><p>What if you want both controllers to share one common limit?</p><p>Rails 8.1 introduces the scope: option for this purpose.</p><h3>Example: Shared rate limit across controllers</h3><p>Create a common API controller:</p><pre># app/controllers/api_controller.rb</pre><pre>class ApiController &lt; ApplicationController<br>  rate_limit to: 100,<br>             within: 1.minute,<br>             scope: &quot;public_api&quot;<br>end</pre><p>Now inherit from it:</p><pre>class Api::PostsController &lt; ApiController<br>  def index<br>    render json: Post.all<br>  end<br>end</pre><pre>class Api::UsersController &lt; ApiController<br>  def index<br>    render json: User.all<br>  end<br>end</pre><p>Both controllers share the same rate-limit scope.</p><p>If a client makes 60 requests to the posts endpoint, only 40 requests remain for the users endpoint during the same rate-limit window.</p><p>The shared counter uses the same scope and client identifier.</p><p><strong>Why is this useful?</strong></p><p>Imagine an application exposing 20 public API endpoints. Instead of allowing 100 requests per endpoint, you can enforce a common limit across the entire API.</p><p>This gives you better control over overall API usage.</p><h3>6. Multiple Rate Limits on the Same Controller</h3><p>Sometimes one rate limit isn’t enough.</p><p>For example, you might want:</p><ul><li>A short-term limit of 3 requests every 2 seconds.</li><li>A longer-term limit of 10 requests every 5 minutes.</li></ul><p>Rails supports multiple rate limits on the same controller.</p><p>Use the name: option to distinguish them.</p><pre>class SessionsController &lt; ApplicationController<br>  rate_limit to: 3,<br>             within: 2.seconds,<br>             name: &quot;short_term&quot;<br>  rate_limit to: 10,<br>             within: 5.minutes,<br>             name: &quot;long_term&quot;<br>  def create<br>    # Login logic<br>  end<br>end</pre><p>Each limit maintains its own counter.</p><p>This is useful when you want to prevent both sudden bursts of traffic and repeated requests over a longer period.</p><h3>7. Where Does Rails Store Rate-Limit Counters?</h3><p>An important question is: How does Rails remember how many requests a client has already made?</p><p>Rails uses an ActiveSupport::Cache store to maintain rate-limit counters.</p><p>By default, it uses the controller cache store, which falls back to the application’s configured cache store.</p><p>For a production application running on multiple servers, using a shared Redis cache can be useful.</p><p>Example:</p><pre>class ApiController &lt; ApplicationController<br>  RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(<br>    url: ENV[&quot;REDIS_URL&quot;]<br>  )<br>  rate_limit to: 100,<br>             within: 1.minute,<br>             store: RATE_LIMIT_STORE<br>end</pre><p>Now the rate-limit counters are stored in Redis.</p><p>Why does this matter?</p><p>Imagine your application runs on three application servers:</p><pre>             Load Balancer<br>                   |<br>          -------------------<br>          |        |        |<br>        Server 1 Server 2 Server 3</pre><p>If each server maintains its own independent counters, a client might bypass the intended limit by sending requests to different servers.</p><p>Using a shared Redis cache allows all three servers to access the same counters.</p><p>Make sure Redis is configured with appropriate availability, memory, and eviction settings for your production workload.</p><h3>8. Rails Rate Limiting vs Rack::Attack</h3><p>Before Rails introduced built-in rate limiting, developers commonly used gems such as Rack::Attack.</p><p>Does Rails’ built-in functionality mean you no longer need Rack::Attack?</p><p>Not necessarily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*yxvrO7syH-h2brHMAabETg.png" /></figure><p>For straightforward controller-level rate limiting, Rails’ built-in functionality is often sufficient.</p><p>If you need advanced request filtering, blocklists, safelists, or more complex throttling rules, Rack::Attack is still worth considering.</p><h3>9. When Should You Use Rails Built-in Rate Limiting?</h3><p>Here are some practical use cases:</p><p><strong>Login endpoints</strong></p><p>Prevent repeated login attempts that could indicate brute-force activity.</p><p><strong>Password reset endpoints</strong></p><p>Avoid excessive password reset requests.</p><p><strong>Public APIs</strong></p><p>Control how frequently clients can access your API.</p><p><strong>Registration endpoints</strong></p><p>Reduce automated account creation attempts.</p><p><strong>Expensive operations</strong></p><p>Protect endpoints that perform costly database queries or external API calls.</p><p>Remember that rate limiting is only one layer of application protection. You should also implement authentication, authorization, input validation, monitoring, and appropriate infrastructure-level protections.</p><h3>Conclusion</h3><p>Rails makes basic rate limiting easier by providing the rate_limit method directly in Action Controller.</p><p>With Rails 8.1, the new scope: option makes it possible to share rate-limit counters across multiple controllers.</p><p>The key takeaways:</p><ul><li>Use rate_limit to restrict requests within a time window.</li><li>Use by: to customize client identification.</li><li>Use with: to customize the response.</li><li>Use scope: to share limits across controllers.</li><li>Use store: to configure a shared cache such as Redis.</li><li>Use name: when defining multiple limits on one controller.</li></ul><p>You don’t always need an additional gem to protect your Rails endpoints from excessive requests.</p><p>Sometimes, the framework already provides the functionality you need.</p><p><strong>Have you used Rails’ built-in rate limiting, or do you prefer Rack::Attack? Share your experience in the comments!</strong></p><h3>References</h3><ul><li><a href="https://api.rubyonrails.org/v8.1.3/classes/ActionController/RateLimiting/ClassMethods.html">Rails 8.1 Action Controller Rate Limiting API</a></li><li><a href="https://rubyrubyrubyruby.dev/rails/8.1/actionpack/CHANGELOG_md.html">Rails 8.1 Action Pack Changelog</a></li><li><a href="https://github.com/rack/rack-attack">Rack::Attack GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f17e808416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 8.1: Using only_columns to Control Which Database Columns Active Record Uses]]></title>
            <link>https://medium.com/@yashika270499/rails-8-1-using-only-columns-to-control-which-database-columns-active-record-uses-88145469d5cc?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/88145469d5cc</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 09:08:17 GMT</pubDate>
            <atom:updated>2026-11-02T09:08:17.108Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with legacy databases or large Rails applications, a model may have more database columns than the application actually needs.</p><p>Some columns might belong to an older feature, a third-party integration, or a database structure shared by multiple applications.</p><p>Traditionally, Rails developers could use ignored_columns to tell Active Record which columns to ignore. With <strong>Rails 8.1,</strong> only_columns <strong>provides the opposite approach: explicitly list the columns a model should use.</strong></p><p>Let’s understand how it works, how to test it in the Rails console, and when it can be useful.</p><h3>1. What Is only_columns in Rails 8.1?</h3><p>ActiveRecord::Base.only_columns allows you to specify the database columns that a model should recognize and use.</p><p>Instead of listing the columns you want to ignore, you list the columns you want Active Record to use.</p><p>Consider a users table with these columns:</p><pre>id<br>name<br>email<br>phone<br>address<br>legacy_reference<br>external_customer_id<br>created_at<br>updated_at</pre><p>Suppose your application only needs:</p><ul><li>id</li><li>name</li><li>email</li><li>created_at</li><li>updated_at</li></ul><p>You can explicitly define that list in your model.</p><h3>2. How to Use only_columns</h3><p>Let’s use a User model as an example.</p><p>app/models/user.rb</p><pre>class User &lt; ApplicationRecord<br>  self.only_columns = %w[<br>    id<br>    name<br>    email<br>    created_at<br>    updated_at<br>  ]<br>end</pre><p>Now, Active Record uses the configured column list when defining model attributes and constructing SQL queries.</p><p>The database schema itself remains unchanged. The phone, address, legacy_reference, and external_customer_id columns still exist in the database.</p><p>The difference is that this model is configured to work with an explicitly defined subset of those columns.</p><h3>3. Test It in the Rails Console</h3><p>One of the easiest ways to understand this feature is to inspect the model directly.</p><p>Start the Rails console:</p><pre>bin/rails console</pre><p>Check the configured columns:</p><pre>User.only_columns</pre><p>Expected output:</p><pre>[&quot;id&quot;, &quot;name&quot;, &quot;email&quot;, &quot;created_at&quot;, &quot;updated_at&quot;]</pre><p>You can also inspect the model’s recognized column names:</p><pre>User.column_names</pre><p>The result reflects the columns Active Record recognizes for this model, subject to the configured column list.</p><p>To inspect the attributes of a new record:</p><pre>user = User.new</pre><pre>user.attributes.keys</pre><p>The attribute list should reflect the configured columns rather than every column in the database table.</p><p><strong>This is useful when debugging a model in the Rails console:</strong> you can check which columns the model is configured to use without changing the underlying database schema.</p><h3>4. Why Is This Useful?</h3><h3>A. Working with legacy databases</h3><p>Imagine you’re maintaining an application that has been running for several years.</p><p>Its database contains columns left behind by older features:</p><pre>users<br>-----<br>id<br>name<br>email<br>old_subscription_id<br>legacy_status<br>deprecated_reference<br>created_at<br>updated_at</pre><p>Your current application only needs the user’s basic information.</p><p>With only_columns, you can explicitly declare the columns that the model should use.</p><p>This makes the intended model schema easier to understand and can reduce accidental dependencies on legacy columns.</p><h3>B. Working with shared database schemas</h3><p>Some applications share a database with another service or application.</p><p>For example, your Rails application might use a customers table that also contains columns maintained by an external integration.</p><p>You may not want your application model to depend on every column in that shared table.</p><p>An explicit column list helps document the subset that your application expects to use.</p><p>Remember, this does not prevent other applications or direct SQL queries from accessing the remaining database columns.</p><h3>C. Making schema changes safer</h3><p>Database changes often require careful coordination between deployments.</p><p>Suppose you’re planning to remove an obsolete column.</p><p>Rather than immediately removing the column from the database, you can first update the application so its model no longer depends on it.</p><p>A possible rollout is:</p><ol><li>Identify the columns the application actually needs.</li><li>Configure only_columns to list those columns.</li><li>Deploy the application and verify that it no longer depends on the obsolete column.</li><li>Check other applications, background jobs, reports, and database queries for dependencies.</li><li>Remove the obsolete column in a subsequent deployment when it is safe to do so.</li></ol><p>This approach can make a schema migration easier to coordinate, especially when multiple application versions or services share a database.</p><p>However, only_columns does not automatically make a migration safe. You still need to verify that no other code depends on the column.</p><h3>5. How Is only_columns Different from ignored_columns?</h3><p>Rails already provides ignored_columns, so why introduce another option?</p><p>The difference is how you express your intention.</p><h3>Using ignored_columns</h3><pre>class User &lt; ApplicationRecord<br>  self.ignored_columns = %w[<br>    legacy_reference<br>    deprecated_reference<br>  ]<br>end</pre><p>This tells Active Record to ignore the listed columns.</p><p>It’s convenient when most columns remain relevant and only a few need to be excluded.</p><h3>Using only_columns</h3><pre>class User &lt; ApplicationRecord<br>  self.only_columns = %w[<br>    id<br>    name<br>    email<br>    created_at<br>    updated_at<br>  ]<br>end</pre><p>This explicitly lists the columns the model should use.</p><p>It’s convenient when you want to define a known subset rather than maintain a list of columns to exclude.</p><p>Feature</p><p>ignored_columns</p><p>only_columns</p><p>Approach</p><p>List columns to ignore</p><p>List columns to use</p><p>Best suited for</p><p>Excluding a small number of columns</p><p>Explicitly defining the model’s column set</p><p>Database schema</p><p>Unchanged</p><p>Unchanged</p><p>Can be combined with the other option?</p><p>No; use one approach per model</p><p>No; use one approach per model</p><p>Choose the approach that best communicates your application’s intent.</p><h3>6. Is only_columns a Security Feature?</h3><p>No. This distinction is important.</p><p>Although only_columns restricts the columns Active Record uses for a model, <strong>it should not be treated as a security or authorization mechanism</strong>.</p><p>For example, suppose your users table contains:</p><pre>id<br>name<br>email<br>admin<br>password_digest</pre><p>Configuring a model to use only id, name, and email does not replace proper authorization, access control, or protection of sensitive information.</p><p>You should still implement appropriate authorization policies, validate permitted input, and protect sensitive attributes.</p><p>Use only_columns to control the model&#39;s expected database columns, not to enforce who can access data.</p><h3>7. Things to Keep in Mind</h3><p>Before adopting only_columns, consider the following:</p><ul><li><strong>Associations:</strong> Verify that the columns needed for association loading and joins are included.</li><li><strong>Primary keys:</strong> Include the primary key or all required composite primary key columns.</li><li><strong>Timestamps:</strong> Include created_at and updated_at if the model relies on them.</li><li><strong>Background jobs and callbacks:</strong> Check whether callbacks or other application code depend on excluded attributes.</li><li><strong>Schema changes:</strong> Confirm that other applications and queries no longer depend on a column before removing it from the database.</li><li><strong>Rails version:</strong> Use a patched Rails release. Rails 8.1.4 includes a fix ensuring that only_columns is respected when constructing the SELECT clause. Earlier Rails 8.1 versions may not handle this correctly in all queries.</li></ul><p>Also, test the behavior with your actual model and associations before applying it to production.</p><h3>Conclusion</h3><p>Rails 8.1’s only_columns provides an explicit way to tell Active Record which database columns a model should use.</p><p>It can be useful when working with legacy tables, shared schemas, and staged database changes.</p><p>The main takeaway is simple:</p><p>ignored_columns <strong>tells Rails what to leave out.</strong> only_columns <strong>tells Rails what to work with.</strong></p><p>If you maintain Rails applications with evolving database schemas, this is a feature worth understanding and testing.</p><p>For more details, see the <a href="https://guides.rubyonrails.org/8_1_release_notes.html">Rails 8.1 Release Notes</a> and the <a href="https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html">Active Record ModelSchema API</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88145469d5cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to Choose Optimistic vs. Pessimistic Locking in Ruby on Rails]]></title>
            <link>https://medium.com/@yashika270499/when-to-choose-optimistic-vs-pessimistic-locking-in-ruby-on-rails-972bfd38459d?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/972bfd38459d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 12:35:59 GMT</pubDate>
            <atom:updated>2026-10-22T12:35:59.070Z</atom:updated>
            <content:encoded><![CDATA[<p>Not every concurrent database update needs the same locking strategy.</p><p>Imagine two users trying to book the last available seat on a flight. Both see that the seat is available and click “Book” almost simultaneously. Without proper concurrency control, both requests might attempt to reserve the same seat.</p><p>Ruby on Rails provides two common locking strategies to handle these situations: <strong>optimistic locking</strong> and <strong>pessimistic locking</strong>.</p><p>But the important question isn’t just how they work. It’s <strong>when should you choose one over the other?</strong></p><p>Let’s explore the differences through practical Rails examples.</p><h3>1. When Should You Choose Optimistic Locking?</h3><p>Choose optimistic locking when conflicts are relatively rare and you want to detect conflicting updates without locking a database record in advance.</p><p>Rails supports optimistic locking using a lock_version column.</p><h3>Real-world example: Editing a product</h3><p>Imagine two administrators editing the same product in an e-commerce application.</p><ul><li>Admin A opens the product and sees its price as ₹500.</li><li>Admin B opens the same product and sees its price as ₹500.</li><li>Admin A changes the price to ₹550 and saves.</li><li>Admin B changes the price to ₹600 and attempts to save.</li></ul><p>Without concurrency control, Admin B could overwrite Admin A’s update without realizing it.</p><p>With optimistic locking, Rails detects that the record has changed since Admin B loaded it and raises ActiveRecord::StaleObjectError.</p><h3>Implementation in Rails</h3><p>First, add a lock_version column:</p><pre>class AddLockVersionToProducts &lt; ActiveRecord::Migration[7.2]<br>  def change<br>    add_column :products, :lock_version,<br>               :integer, default: 0, null: false<br>  end<br>end</pre><p>Rails automatically uses this column for optimistic locking.</p><pre>product_a = Product.find(1)<br>product_b = Product.find(1)<br><br>product_a.update!(price: 550)<br>product_b.update!(price: 600)<br># Raises ActiveRecord::StaleObjectError</pre><p>The second update fails because the record’s version has changed.</p><h3>Choose optimistic locking when:</h3><ul><li>Multiple users may edit the same record, but simultaneous updates are uncommon.</li><li>Users spend time editing forms before saving.</li><li>You want to detect stale updates instead of blocking other transactions.</li><li>Your application can ask users to reload or resolve conflicting changes.</li></ul><p><strong>Typical use cases:</strong> Product descriptions, user profiles, document editing, and administrative settings.</p><h3>2. When Should You Choose Pessimistic Locking?</h3><p>Choose pessimistic locking when concurrent operations are likely and conflicting updates must be serialized.</p><p>Instead of allowing multiple transactions to modify the same record and detecting conflicts afterward, pessimistic locking acquires a database lock before performing the critical operation.</p><p>Rails provides pessimistic locking through methods such as with_lock and lock.</p><h3>Real-world example: Booking the last available seat</h3><p>Imagine a flight has only one seat remaining. Two customers try to book it at nearly the same time.</p><p>The application must ensure that only one customer can successfully reserve that seat.</p><pre>FlightSeat.transaction do<br>  seat = FlightSeat.lock.find(seat_id)<br>raise &quot;Seat already booked&quot; if seat.booked?<br>  seat.update!(booked: true)<br>end</pre><p>The lock method issues a locking read, typically using SELECT ... FOR UPDATE on PostgreSQL. If another transaction already holds a conflicting row lock, the second transaction waits until that lock is released.</p><p>Once the first transaction commits, the second transaction can proceed and check the latest committed state. It then sees that the seat is booked and cannot reserve it again.</p><p>The lock is released when the transaction ends.</p><h3>Choose pessimistic locking when:</h3><ul><li>Concurrent updates to the same record are likely.</li><li>An operation involves limited resources, such as seats, inventory, or account balances.</li><li>Conflicting operations must be serialized to maintain consistency.</li><li>Retrying failed operations would be expensive or difficult.</li></ul><p><strong>Typical use cases:</strong> Inventory deductions, seat reservations, financial balance updates, and processing shared resources.</p><h3>3. Can You Use Both Locking Strategies in One Application?</h3><p>Yes. Different operations can require different strategies.</p><p>For example, in an e-commerce application:</p><ul><li><strong>Editing product descriptions:</strong> Optimistic locking, because concurrent edits are relatively uncommon.</li><li><strong>Reducing stock during checkout:</strong> Pessimistic locking when you need to serialize updates to a specific inventory row.</li><li><strong>Updating account settings:</strong> Optimistic locking, especially when users edit forms over a longer period.</li><li><strong>Allocating a limited resource:</strong> Pessimistic locking when competing transactions must check and claim the same resource safely.</li></ul><p>Choose the strategy based on the operation’s concurrency characteristics and business requirements, rather than applying one locking strategy to every model.</p><h3>4. What Should You Consider Before Choosing?</h3><p>Before implementing either strategy, ask yourself these questions:</p><ol><li><strong>How frequently can conflicts occur?</strong> If simultaneous updates are rare, optimistic locking may be sufficient.</li><li><strong>What happens if an update fails?</strong> If a user can safely reload and retry, optimistic locking is often appropriate.</li><li><strong>Must the operation be serialized?</strong> If competing transactions must check and claim a resource in sequence, pessimistic locking may be a better fit.</li><li><strong>How long will the transaction run?</strong> Keep pessimistic locking transactions short. Never hold a database lock while waiting for user input or making slow external HTTP calls.</li><li><strong>What other safeguards are needed?</strong> Database constraints, atomic updates, and appropriate isolation levels can be essential regardless of the locking strategy.</li></ol><h3>Conclusion</h3><p>The choice between optimistic and pessimistic locking depends on how your application handles concurrency.</p><p>Use <strong>optimistic locking</strong> when conflicts are uncommon and you can detect and resolve stale updates. Use <strong>pessimistic locking</strong> when concurrent operations must be serialized to protect shared resources.</p><p>The goal isn’t to lock everything. It’s to select the simplest concurrency-control strategy that preserves your application’s data integrity without unnecessarily reducing performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972bfd38459d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Merge vs Rebase: What Actually Happens to Your Commit History?]]></title>
            <link>https://medium.com/@yashika270499/git-merge-vs-rebase-what-actually-happens-to-your-commit-history-a2e85a3a6759?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e85a3a6759</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[difference]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 07:03:15 GMT</pubDate>
            <atom:updated>2026-09-30T08:47:36.915Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with Git for a while, you’ve probably seen commands like:</p><pre>git merge main</pre><p>and:</p><pre>git rebase main</pre><p>Both commands can be used to bring changes from one branch into another.</p><p>So a common question is:</p><blockquote><strong><em>If both merge and rebase bring my branch up to date, what’s actually the difference?</em></strong></blockquote><p>The short answer is:</p><p><strong>Merge combines histories. Rebase rewrites your branch’s history by replaying your commits on top of another branch.</strong></p><p>But that sentence alone isn’t enough to really understand the difference.</p><p>Let’s start from the beginning.</p><h3>First, understand what a Git branch really is</h3><p>Before comparing merge and rebase, let’s understand one important thing.</p><p>A Git branch is basically a <strong>movable pointer to a commit</strong>.</p><p>Suppose we have:</p><pre>A → B → C<br>        ↑<br>       main</pre><p>main currently points to commit C.</p><p>Now we create a feature branch:</p><pre>A → B → C<br>        ↑<br>       main<br>        ↑<br>      feature</pre><p>Both branches initially point to the same commit.</p><p>Now you make a change on the feature branch:</p><pre>A → B → C → D<br>        ↑       ↑<br>       main   feature</pre><p>feature has moved forward, while main has stayed at C.</p><p>This is the basic idea behind Git branching.</p><h3>Now let’s create a real situation</h3><p>Imagine you’re working on a Rails application.</p><p>You create a branch:</p><pre>git switch -c feature/login</pre><p>At that moment:</p><pre>A → B → C<br>        ↑<br>       main<br>        ↑<br>   feature/login</pre><p>You make two commits:</p><pre>A → B → C → D → E<br>        ↑         ↑<br>       main   feature/login</pre><p>Maybe:</p><pre>D = Add login form<br>E = Add authentication logic</pre><p>Meanwhile, another developer adds a change to main:</p><pre>A → B → C → F<br>        ↑    ↑<br>       main</pre><p>Now your repository looks like this:</p><pre>              D → E<br>             ↗     ↑<br>A → B → C<br>             ↘<br>              F<br>              ↑<br>             main</pre><p>More clearly:</p><pre>              D → E   feature/login<br>             /<br>A → B → C<br>             \<br>              F       main</pre><p>This is called <strong>diverged history</strong>.</p><p>Your feature branch and main have moved in different directions.</p><p>Now you need to bring main&#39;s changes into your feature branch.</p><p>That’s where <strong>merge and rebase</strong> come in.</p><h3>Option 1: Git Merge</h3><p>You are on your feature branch:</p><pre>git switch feature/login</pre><p>Then:</p><pre>git merge main</pre><p>Git takes the histories from both branches and creates a new merge commit when a true merge is required.</p><p>The history becomes:</p><pre>              D → E<br>             /     \<br>A → B → C           M<br>             \     /<br>              F ──</pre><p>M is the merge commit.</p><p>The important thing is:</p><p><strong>Git keeps both histories as they actually happened.</strong></p><p>Your feature work happened on one branch.</p><p>The main work happened on another branch.</p><p>The merge commit records that those two lines were brought together.</p><p>Git’s documentation describes merge as joining development histories and, for a true merge, creating a commit with both branch tips as parents.</p><h3>What does the merge commit mean?</h3><p>This is important for beginners.</p><p>Suppose you see:</p><pre>A → B → C → F<br>        \<br>         D → E<br>              \<br>               M</pre><p>You might wonder:</p><blockquote><em>“What code is inside M?”</em></blockquote><p>The merge commit represents the <strong>combined result of both branches</strong>.</p><p>Conceptually:</p><pre>main changes<br>     +<br>feature changes<br>     ↓<br>combined result</pre><p>The merge commit has two parents:</p><pre>        M<br>       / \<br>      E   F</pre><p>That is one of the important differences between merge and rebase.</p><h3>Fast-forward merge</h3><p>There is another situation beginners should know about.</p><p>Suppose main hasn&#39;t changed since you created your feature branch:</p><pre>A → B → C<br>        ↑<br>       main<br>        \<br>         D → E<br>              ↑<br>           feature</pre><p>If you run:</p><pre>git switch main<br>git merge feature</pre><p>Git doesn’t need to create a merge commit.</p><p>It can simply move main forward:</p><pre>A → B → C → D → E<br>                ↑<br>             main<br>             feature</pre><p>This is called a <strong>fast-forward merge</strong>.</p><p>There is no divergent history to combine.</p><p>Git simply moves the branch pointer forward. Git’s merge documentation distinguishes this from a true merge commit.</p><h3>Option 2: Git Rebase</h3><p>Now let’s go back to our original situation.</p><p>We have:</p><pre>              D → E<br>             /<br>A → B → C<br>             \<br>              F<br>              ↑<br>             main</pre><p>You are on:</p><pre>feature/login</pre><p>Instead of merging main, you can run:</p><pre>git rebase main</pre><p>This sounds complicated, but the basic idea is surprisingly simple.</p><p><strong>Rebase takes your feature commits and replays them on top of the latest </strong><strong>main.</strong></p><p>Git’s official documentation describes rebase as taking the changes introduced by commits on one branch and replaying them on another base.</p><p>So originally:</p><pre>              D → E<br>             /<br>A → B → C<br>             \<br>              F</pre><p>After:</p><pre>git rebase main</pre><p>Git effectively does this:</p><pre>A → B → C → F → D&#39; → E&#39;</pre><p>Now:</p><pre>A → B → C → F → D&#39; → E&#39;<br>                  ↑      ↑<br>              new D    new E</pre><p>Your feature commits have been replayed on top of the latest main.</p><h3>Wait… why are D and E now D’ and E’?</h3><p>This is one of the most important concepts in understanding rebase.</p><p>You originally had:</p><pre>D<br>E</pre><p>After rebase, Git creates <strong>new commits</strong> based on the same changes:</p><pre>D&#39;<br>E&#39;</pre><p>They may contain the same code changes, but they are <strong>different Git commits</strong>.</p><p>Why?</p><p>Because a Git commit is not identified only by its code changes.</p><p>Its identity also depends on its parent and other metadata.</p><p>Before rebase:</p><pre>C → D → E</pre><p>After rebase:</p><pre>C → F → D&#39; → E&#39;</pre><p>Since D&#39; has a different parent than D, its commit identity changes.</p><p>This is why rebase <strong>rewrites history</strong>.</p><h3>The easiest way to remember it</h3><p>Think of <strong>merge</strong> as:</p><blockquote><em>“Let’s combine these two roads.”</em></blockquote><p>And <strong>rebase</strong> as:</p><blockquote><em>“Let’s move my road so it starts from the latest point on the other road.”</em></blockquote><h3>Merge</h3><pre>        D → E<br>      /     \<br>A → B → C    M<br>      \     /<br>       F ──</pre><h3>Rebase</h3><p>Before:</p><pre>        D → E<br>      /<br>A → B → C → F</pre><p>After:</p><pre>A → B → C → F → D&#39; → E&#39;</pre><h3>A real-world analogy</h3><p>Imagine you’re writing a book.</p><p>You started writing Chapter 5 based on version 1 of the book.</p><p>Meanwhile, another writer updated Chapters 1–4.</p><p>You now have two choices.</p><h3>Merge</h3><p>You say:</p><blockquote><em>“Let’s keep both versions of history and combine the work.”</em></blockquote><p>The final history shows that two people worked in parallel and their work was combined later.</p><h3>Rebase</h3><p>You say:</p><blockquote><em>“Let’s take my Chapter 5 changes and apply them to the newest version of Chapters 1–4.”</em></blockquote><p>Now the history looks as though your Chapter 5 work happened after the latest version.</p><p>That’s essentially what rebase does to commits.</p><h3>Merge vs Rebase at a glance</h3><p>MergeRebaseCombines branchesYesYesCreates merge commitUsually, when histories divergeNo, not for the rebased commitsKeeps original branch historyYesNoRewrites commitsNoYesProduces linear historyNot necessarilyUsuallySafer for shared/published historyGenerallyRequires cautionUseful for cleaning local historyLess soYes</p><p>The biggest difference is <strong>history</strong>.</p><h3>Does rebase change the final code?</h3><p>This is another common beginner question.</p><p>Suppose both operations are performed correctly and conflicts are resolved consistently.</p><p>The final project files can be the same.</p><p>For example:</p><pre>Merge result:</pre><pre>A → B → C → F → M<br></pre><pre>Rebase result:</pre><pre>A → B → C → F → D&#39; → E&#39;</pre><p>The commit history is different, but the final snapshot can represent the same combined code.</p><p>Git’s documentation explicitly notes that the final snapshot can be the same while the history differs.</p><p>So the major difference isn’t:</p><blockquote><em>“Which one gives me the correct code?”</em></blockquote><p>It is:</p><blockquote><strong><em>“How do I want the project’s history to look?”</em></strong></blockquote><h3>Why do developers like rebase?</h3><p>One major reason is <strong>cleaner history</strong>.</p><p>Imagine your project has:</p><pre>main<br> ├── feature A<br> ├── feature B<br> ├── feature C<br> └── feature D</pre><p>If everyone frequently merges main into their feature branches, history can become filled with commits like:</p><pre>Merge branch &#39;main&#39; into feature/login<br>Merge branch &#39;main&#39; into feature/login<br>Merge branch &#39;main&#39; into feature/login</pre><p>The history becomes harder to read.</p><p>With rebase, a developer can update their local feature branch:</p><pre>git fetch origin<br>git rebase origin/main</pre><p>and keep their own commits on top of the latest main.</p><p>The result can look much more linear:</p><pre>A → B → C → D → E → F → G</pre><p>rather than:</p><pre>A → B → C ─────────────── M<br>         \              /<br>          D → E → F → G</pre><p>Git’s documentation specifically notes that rebasing can produce a cleaner, linear history.</p><h3>But if rebase is cleaner, why not always use it?</h3><p>Because <strong>rebase rewrites history</strong>.</p><p>This is where beginners can get into trouble.</p><p>Imagine you’ve already pushed:</p><pre>A → B → C → D</pre><p>to GitHub.</p><p>Another developer has based their work on commit D.</p><p>Now you rebase your branch.</p><p>Git may create:</p><pre>A → B → C → D&#39;</pre><p>D&#39; is a new commit.</p><p>From Git’s perspective:</p><pre>D ≠ D&#39;</pre><p>You have rewritten the branch’s history.</p><p>If you force-push that rewritten history, the other developer may have to deal with the changed commit ancestry.</p><p>That’s why rebasing <strong>shared/published branches requires caution</strong>. Git’s documentation recommends avoiding rebasing commits that have already been published unless you understand the consequences.</p><h3>A simple rule for beginners</h3><p>Remember this:</p><blockquote><strong><em>Rebase your private/local work. Be careful rebasing shared work.</em></strong></blockquote><p>For example:</p><pre>feature/login</pre><p>is your personal branch.</p><p>You can generally rebase it while you’re developing.</p><p>But:</p><pre>main</pre><p>is shared by the whole team.</p><p>Rewriting main history is usually a very different situation.</p><h3>What happens when there is a conflict?</h3><p>Both merge and rebase can have conflicts.</p><p>Suppose you changed:</p><pre>def welcome_message<br>  &quot;Welcome!&quot;<br>end</pre><p>and another branch changed the same lines:</p><pre>def welcome_message<br>  &quot;Welcome back!&quot;<br>end</pre><p>Git may not know which version you want.</p><p>You’ll see a conflict.</p><p>With merge:</p><pre>git merge main</pre><p>you resolve the conflict and then:</p><pre>git add .<br>git commit</pre><p>or use:</p><pre>git merge --continue</pre><p>depending on the merge state/workflow.</p><p>With rebase:</p><pre>git rebase main</pre><p>you resolve the conflict and then:</p><pre>git add .<br>git rebase --continue</pre><p>If you decide that you don’t want to continue the rebase:</p><pre>git rebase --abort</pre><p>Git provides --abort specifically to stop a rebase and attempt to restore the state from before the rebase.</p><h3>Why can rebase feel harder during conflicts?</h3><p>Because rebase processes your commits <strong>one at a time</strong>.</p><p>Imagine your feature has:</p><pre>D → E → F</pre><p>During rebase, Git essentially replays:</p><pre>D&#39;<br>E&#39;<br>F&#39;</pre><p>If D conflicts, Git stops.</p><p>You resolve it.</p><p>Then:</p><pre>git rebase --continue</pre><p>Git moves to the next commit.</p><p>If E also conflicts, you resolve that one too.</p><p>So you may encounter multiple conflict resolutions during one rebase.</p><p>This happens because rebase replays the commits individually.</p><h3>What happens during a merge conflict?</h3><p>Merge generally considers the two branch tips and their common ancestor to combine the changes.</p><p>For example:</p><pre>              D → E<br>            /<br>A → B → C<br>            \<br>             F → G</pre><p>Git compares the relevant histories and attempts to produce one combined result.</p><p>If Git can’t automatically determine the correct result, it stops and asks you to resolve the conflict.</p><p>Git’s normal merge strategy is a three-way merge using the two branch tips and their merge base.</p><h3>Rebase is not “better merge”</h3><p>This is an important point.</p><p>You will sometimes hear:</p><blockquote><em>“Always rebase. Merge is bad.”</em></blockquote><p>That’s an oversimplification.</p><p>Merge and rebase solve related problems but have different effects on history.</p><p>Git’s own documentation doesn’t say that one is universally better. The appropriate choice depends on the project and team workflow.</p><p>A team may deliberately prefer merge commits because they want to preserve the history of how branches were integrated.</p><p>Another team may prefer a linear history because it makes the project easier to navigate.</p><p>Neither approach is universally correct.</p><h3>Example: working on a feature in a team</h3><p>Suppose you’re working on:</p><pre>feature/payment</pre><p>Meanwhile, main has received new changes.</p><p>You want the latest main changes before opening/updating your PR.</p><p>You can do:</p><pre>git fetch origin<br>git rebase origin/main</pre><p>Your history becomes:</p><pre>main:<br>A → B → C → D</pre><pre>feature:<br>            E → F</pre><p>After:</p><pre>git rebase origin/main</pre><p>you get:</p><pre>A → B → C → D → E&#39; → F&#39;</pre><p>Your feature commits now sit on top of the latest main.</p><h3>What if you use merge instead?</h3><p>You could instead do:</p><pre>git fetch origin<br>git merge origin/main</pre><p>The history could become:</p><pre>          E → F<br>         /     \<br>A → B → C → D → M</pre><p>The branch contains the same combined work, but the history records the merge explicitly.</p><h3>What does git pull --rebase mean?</h3><p>You may also have seen:</p><pre>git pull --rebase</pre><p>This is another source of confusion.</p><p>Normally:</p><pre>git pull</pre><p>essentially does:</p><pre>git fetch<br>+<br>integration</pre><p>Depending on your configuration/options, that integration can use merge or rebase. Git documents git pull --rebase as fetching and then rebasing the local work onto the fetched branch.</p><p>So:</p><pre>git pull --rebase</pre><p>roughly means:</p><pre>Get latest remote changes<br>        ↓<br>Put my local commits on top of them</pre><p>For example:</p><p>Before:</p><pre>remote: A → B → C<br>local:          \<br>                 D → E</pre><p>After:</p><pre>A → B → C → D&#39; → E&#39;</pre><h3>git pull vs git pull --rebase</h3><p>This is a useful distinction:</p><h3>Regular pull</h3><p>Depending on configuration:</p><pre>git pull</pre><p>can integrate remote changes using merge.</p><p>You might get:</p><pre>A → B → C ───── M<br>         \     /<br>          D → E</pre><h3>Pull with rebase</h3><pre>git pull --rebase</pre><p>gives you:</p><pre>A → B → C → D&#39; → E&#39;</pre><p>Again, the goal is usually to avoid unnecessary merge commits in your local branch history.</p><h3>What should a fresher use?</h3><p>For someone new to Git, I recommend first becoming comfortable with <strong>merge</strong>.</p><p>Understand:</p><pre>git switch<br>git fetch<br>git merge<br>git pull<br>git push</pre><p>Once you understand branches and commits, learn rebase.</p><p>Why?</p><p>Because merge is conceptually closer to:</p><blockquote><em>“These two branches have changes. Combine them.”</em></blockquote><p>Rebase requires understanding:</p><blockquote><em>“Take these existing commits and recreate them on a different base.”</em></blockquote><p>Once that mental model clicks, rebase becomes much easier.</p><h3>A simple decision guide</h3><h3>Use merge when:</h3><ul><li>You want to preserve the actual branching history.</li><li>The branch is shared by multiple developers.</li><li>You don’t want to rewrite existing history.</li><li>Your team prefers merge commits.</li><li>You are integrating a completed branch into another branch.</li></ul><p>Example:</p><pre>git switch main<br>git merge feature/login</pre><h3>Use rebase when:</h3><ul><li>You’re updating your own feature branch.</li><li>You want a cleaner linear history.</li><li>Your commits haven’t been shared yet.</li><li>Your team follows a rebase-based workflow.</li><li>You want to replay your work on top of the latest main.</li></ul><p>Example:</p><pre>git switch feature/login<br>git fetch origin<br>git rebase origin/main</pre><h3>One important warning about force push</h3><p>After rebasing a branch that has already been pushed, you may need:</p><pre>git push --force-with-lease</pre><p>Notice that I used:</p><pre>--force-with-lease</pre><p>rather than:</p><pre>--force</pre><p>--force-with-lease provides an additional safety check so you don&#39;t blindly overwrite a remote branch that has moved unexpectedly.</p><p>But even with --force-with-lease, you should understand that you&#39;re rewriting the remote branch&#39;s history.</p><p>Don’t casually rebase and force-push a branch that other developers are actively using.</p><h3>The easiest mental model</h3><p>If you remember only one thing from this article, remember this:</p><h3>Merge</h3><blockquote><strong><em>Keep both histories and connect them.</em></strong></blockquote><pre>      D → E<br>     /     \<br>A → B       M<br>     \     /<br>      F → G</pre><h3>Rebase</h3><blockquote><strong><em>Take my commits and replay them on top of the latest base.</em></strong></blockquote><pre>Before:</pre><pre>      D → E<br>     /<br>A → B → C → F</pre><pre>After:</pre><pre>A → B → C → F → D&#39; → E&#39;</pre><h3>Final comparison</h3><p>Imagine you and another developer start from the same point:</p><pre>A → B</pre><p>You create:</p><pre>C → D</pre><p>They create:</p><pre>E → F</pre><h3>With merge</h3><p>Git says:</p><blockquote><em>“You both worked from B. I’ll combine the two histories.”</em></blockquote><pre>        C → D<br>      /     \<br>A → B       M<br>      \     /<br>       E → F</pre><h3>With rebase</h3><p>Git says:</p><blockquote><em>“I’ll take your C and D changes and replay them after E and F.”</em></blockquote><pre>A → B → E → F → C&#39; → D&#39;</pre><p>That’s the core difference.</p><h3>Conclusion</h3><p>git merge and git rebase aren&#39;t simply two commands that do the same thing.</p><p>They represent two different approaches to <strong>history</strong>.</p><p><strong>Merge preserves the branching story.</strong></p><p><strong>Rebase rewrites your branch so your commits appear on top of another branch.</strong></p><p>If you’re working on your own feature branch, rebasing onto the latest main can give you a clean, linear history.</p><p>If you’re working with shared history where preserving existing commits and branch relationships matters, merging can be the safer choice.</p><p>The most important thing isn’t memorizing:</p><pre>git merge</pre><p>versus:</p><pre>git rebase</pre><p>It’s understanding what Git is doing to your commit graph.</p><p>Once you understand the graph, the commands become much easier to remember.</p><h3>Quick cheat sheet</h3><pre># Merge<br>git switch feature/login<br>git merge main</pre><pre># Rebase<br>git switch feature/login<br>git rebase main</pre><pre># Update remote information first<br>git fetch origin</pre><pre># Rebase your feature onto remote main<br>git rebase origin/main</pre><pre># Continue after resolving a rebase conflict<br>git add .<br>git rebase --continue</pre><pre># Cancel an ongoing rebase<br>git rebase --abort</pre><pre># Push rewritten history safely<br>git push --force-with-lease</pre><p><strong>Remember:</strong></p><pre>MERGE  → combine histories</pre><pre>REBASE → replay commits on a new base</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e85a3a6759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Rails Transaction Rolled Back. What Happened to the API Call, Email, or Job?]]></title>
            <link>https://medium.com/@yashika270499/your-rails-transaction-rolled-back-what-happened-to-the-api-call-email-or-job-408c6ae49bbe?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/408c6ae49bbe</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 10:00:38 GMT</pubDate>
            <atom:updated>2026-09-23T10:43:32.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a9h32U1f_A3BVBb3" /></figure><p>A database transaction gives us a powerful guarantee:</p><blockquote><em>Either the database changes succeed together, or they are rolled back.</em></blockquote><p>But there is an important boundary that is easy to overlook.</p><p>A database transaction can roll back <strong>database changes</strong>. It cannot automatically roll back an HTTP request that has already reached another service, an email that has already been sent, or a background job that has already been enqueued.</p><p>Consider this:</p><pre>User.transaction do<br> user = User.create!(name: &quot;Yashika&quot;) <br> WelcomeJob.perform_later(user.id) <br><br> raise ActiveRecord::Rollback <br>end</pre><p>The User record is rolled back.</p><p>But depending on when the job was enqueued, the background job may already exist in the queue.</p><p>Now the job can execute with an ID for a record that no longer exists.</p><p>The same class of problem can happen with external HTTP APIs and email delivery.</p><p>This is the problem I wanted to make easier to detect in Rails applications, so I built <strong>TransactionGuard</strong>.</p><h3>The problem: database transactions don’t cover external side effects</h3><p>A typical Rails transaction might look perfectly reasonable:</p><pre>User.transaction do<br> user = User.create! <br> SomeExternalApi.create_user(user) <br> WelcomeMailer.welcome(user).deliver_now<br>end</pre><p>At first glance, everything looks like one atomic operation.</p><p>But it isn’t.</p><p>There are actually multiple systems involved:</p><blockquote>┌──────────────────────┐<br> │ Rails Application │<br> └──────────┬───────────┘<br> │<br> ActiveRecord<br> transaction<br> │<br> ┌────────────┴────────────┐<br> │ │<br> ▼ ▼<br> Database changes External side effects<br> │<br> ┌─────────────┼─────────────┐<br> │ │ │<br> ▼ ▼ ▼<br> HTTP Email Job</blockquote><p>The database can participate in the transaction.</p><p>The external systems generally cannot.</p><p>So if the transaction fails:</p><blockquote>Database<br> ↓<br>ROLLBACK</blockquote><blockquote>HTTP request<br> ↓<br>Already sent</blockquote><blockquote>Email<br> ↓<br>Already sent</blockquote><blockquote>Background job<br> ↓<br>May already be queued</blockquote><p>That’s where subtle production bugs can appear.</p><p>Imagine an application that creates a customer and then synchronizes that customer with an external CRM.</p><pre>Customer.transaction do<br> customer = Customer.create!(name: &quot;Acme&quot;)<br> CRMClient.create_customer(customer) <br> raise ActiveRecord::Rollback <br>end</pre><p>After the rollback:</p><pre>Database: Customer does not exist<br>CRM: Customer may already exist</pre><p>Now the application and the external service disagree.</p><p>This can become even harder to debug when the external operation is hidden inside a service object, callback, mailer, or job.</p><h3>Why background jobs can be particularly tricky</h3><p>Consider:</p><pre>Order.transaction do<br> order = Order.create! <br> OrderConfirmationJob.perform_later(order.id)<br> raise ActiveRecord::Rollback <br>end</pre><p>The database transaction rolls back the order.</p><p>But the job enqueue is a separate operation.</p><p>The job may later execute:</p><pre>OrderConfirmationJob.perform(order.id)</pre><p>and discover that the order doesn’t exist.</p><p>TransactionGuard’s README demonstrates this exact class of problem: the database record can be rolled back while the job has already been enqueued.</p><p>The problem isn’t that background jobs are bad.</p><p>The problem is <strong>when they are triggered</strong>.</p><h3>What about emails?</h3><p>The same problem exists with email delivery.</p><p>For example:</p><pre>User.transaction do <br> user = User.create! <br> UserMailer.welcome(user).deliver_now<br> raise ActiveRecord::Rollback<br>end</pre><p>The database operation can roll back after the email has already been delivered.</p><p>You can end up with:</p><pre>Database:<br>User creation rolled back<br><br>Email:<br>Welcome email already delivered</pre><p>This can create confusing user experiences and difficult-to-reproduce bugs.</p><p>TransactionGuard detects both deliver_now and deliver_later when they occur inside an ActiveRecord transaction.</p><h3>So I built TransactionGuard</h3><p><strong>TransactionGuard</strong> is a Ruby/Rails gem that detects external side effects performed while an ActiveRecord transaction is open.</p><p>The current version detects:</p><ul><li>HTTP requests through Net::HTTP</li><li>Email delivery through Action Mailer</li><li>ActiveJob enqueueing</li><li>ActiveJob immediate execution</li></ul><p>The goal isn’t to automatically fix the code.</p><p>The goal is to make the problem visible during development and testing.</p><p>Repository:</p><p><a href="https://github.com/yashika279/transaction%5C_guard">https://github.com/yashika279/transaction\_guard</a></p><h3>How TransactionGuard works</h3><p>The basic question is surprisingly simple:</p><pre>TransactionGuard::Transaction.open?</pre><p>If an ActiveRecord transaction is currently open, TransactionGuard can identify it and let the relevant detector report the external operation.</p><p>Conceptually:</p><pre>External operation<br>       │<br>       ▼<br>Is TransactionGuard enabled?<br>       │<br>       ▼<br>Is an ActiveRecord transaction open?<br>       │<br>       ├── No → Continue normally<br>       │<br>       └── Yes<br>             │<br>             ▼<br>       Report the operation<br>             │<br>             ▼<br>       warn / raise</pre><p>This keeps the responsibility focused:</p><p><strong>TransactionGuard detects the potentially unsafe operation.</strong></p><p>It doesn’t silently change your application’s behavior.</p><h3>Detecting HTTP requests</h3><p>One of the first detectors I implemented was for Net::HTTP.</p><p>For example:</p><pre>User.transaction do<br>  Net::HTTP.get(URI(&quot;https://example.com&quot;))<br>end</pre><p>TransactionGuard detects the request because it occurs while the transaction is open.</p><p>The HTTP detector wraps common methods such as:GET POST PUT PATCH DELETE HEAD OPTIONS</p><pre>GET<br>POST<br>PUT<br>PATCH<br>DELETE<br>HEAD<br>OPTIONS</pre><p>Internally, the detector checks whether a transaction is open before reporting the operation.</p><p>There is also protection against reporting the same underlying request multiple times when one HTTP method eventually delegates to another internal method.</p><p>That matters because instrumentation should provide useful signals without producing a wall of duplicate warnings.</p><h3>Detecting email delivery</h3><p>The email detector covers:</p><pre>UserMailer.welcome(user).deliver_now</pre><p>and:</p><pre>UserMailer.welcome(user).deliver_later</pre><p>inside a transaction.</p><p>An important detail here is avoiding duplicate reporting.</p><p>deliver_later internally involves ActiveJob, but from the application&#39;s perspective the operation is an <strong>email delivery</strong>.</p><p>TransactionGuard therefore reports it as an email side effect instead of producing an additional warning for the internal ActiveJob enqueue.</p><h3>Detecting ActiveJob operations</h3><p>TransactionGuard also hooks into ActiveJob operations.</p><p>For example:</p><pre>WelcomeJob.perform_later(user.id)</pre><p>inside a transaction is reported as a job enqueue operation.</p><p>It also detects:</p><pre>WelcomeJob.perform_now</pre><p>as a job execution operation.</p><p>The current 0.1.0 implementation specifically targets ActiveJob APIs; direct Sidekiq, Resque, and similar non-ActiveJob APIs are outside the current detector scope.</p><h3>Three modes: warn, raise, and off</h3><p>I wanted the gem to be useful in different development workflows.</p><p>TransactionGuard currently supports three modes:</p><pre>:warn :raise :off</pre><p>The default mode is:</p><h3>Warn mode</h3><pre>TransactionGuard.configure do |config|<br>  config.mode = :warn<br>end</pre><p>The application continues running, but TransactionGuard reports the detected side effect.</p><p>This is useful when introducing the gem into an existing application because you can discover problematic code without immediately breaking development or tests.</p><h3>Raise mode</h3><p>For stricter enforcement:</p><pre>TransactionGuard.configure do |config|<br>  config.mode = :raise<br>end</pre><p>Now an unsafe external side effect causes TransactionGuard to raise an error.</p><p>This can be useful in tests when you want a transaction-side-effect violation to fail fast.</p><h3>Off mode</h3><p>Detection can also be disabled:</p><pre>TransactionGuard.configure do |config|<br>  config.mode = :off<br>end</pre><p>The Rails integration currently defaults to :warn in development and test, and :off in production.</p><h3>Installation</h3><p>Add the gem to your Gemfile:</p><pre>gem &quot;transaction_guard&quot;</pre><p>Then:</p><pre>bundle install</pre><p>For local development, you can also point Rails to a local checkout:</p><pre>gem &quot;transaction_guard&quot;, path: &quot;../transaction_guard&quot;</pre><p>The project is open source and available under the MIT license.</p><h3>What does the warning look like?</h3><p>Suppose we have:</p><pre>User.transaction do<br>  user = User.create!<br><br>  WelcomeJob.perform_later(user.id)<br>end</pre><p>TransactionGuard can report that a job enqueue happened while an ActiveRecord transaction was open.</p><p>The important information is the operation and the caller location.</p><p>That makes the warning actionable:</p><pre>Transaction detected external side effect:<br>Job enqueue<br><br>Caller:<br>app/services/users/create.rb:...</pre><p>Instead of discovering the problem later through a production incident, you can catch it while developing or testing.</p><h3>How should we fix these problems?</h3><p>TransactionGuard intentionally doesn’t automatically move operations outside the transaction.</p><p>That’s an application design decision.</p><p>A common approach is to perform the external operation after the database transaction succeeds.</p><p>For example:</p><pre>user = User.create!<br><br>User.transaction do<br>  user.update!(status: &quot;active&quot;)<br>end<br><br>WelcomeJob.perform_later(user.id)</pre><p>Rails also provides mechanisms such as after_commit, which can be appropriate when an operation should happen only after a successful database commit.</p><p>For more complex distributed workflows, patterns such as:</p><ul><li>transactional outbox</li><li>reliable event publishing</li><li>post-commit job triggering</li></ul><p>can be considered.</p><p>The important idea is:</p><pre>Database transaction<br>        │<br>        ▼<br>Commit succeeds<br>        │<br>        ▼<br>External side effect</pre><p>rather than:</p><pre>Database transaction<br>        │<br>        ├── Database change<br>        │<br>        └── External side effect<br>                │<br>                ▼<br>          Transaction rolls back</pre><p>TransactionGuard doesn’t decide which pattern your application should use. It tells you where the potentially unsafe boundary exists.</p><h3>Why not just use after_commit everywhere?</h3><p>after_commit is useful, but it isn&#39;t a universal solution.</p><p>Applications often have:</p><ul><li>service objects</li><li>callbacks</li><li>mailers</li><li>background jobs</li><li>API clients</li><li>third-party integrations</li><li>shared libraries</li></ul><p>An external operation can be introduced far away from the transaction that eventually rolls back.</p><p>The purpose of TransactionGuard is therefore not to replace Rails transaction patterns.</p><p>It provides a <strong>development-time safety net</strong> that helps identify these boundaries.</p><h3>Current limitations</h3><p>TransactionGuard is intentionally small in its first version.</p><p>The current 0.1.0 implementation focuses on:</p><pre>Net::HTTP<br>Action Mailer<br>ActiveJob</pre><p>Direct clients such as:</p><pre>Faraday<br>HTTParty<br>httpx</pre><p>are not directly hooked in the current version, although clients built on top of Net::HTTP may be detected. Similarly, direct Sidekiq and Resque APIs are not currently detected.</p><p>These are areas that can evolve as the project grows.</p><h3>Testing the gem</h3><p>The project uses RSpec for its test suite and RuboCop for code quality.</p><p>Run the tests with:</p><pre>bundle exec rspec</pre><p>Run RuboCop with:</p><pre>bundle exec rubocop</pre><p>The repository also includes integration coverage around the detectors.</p><h3>What I learned building it</h3><p>The interesting part of this project wasn’t just writing three detectors.</p><p>It was thinking about <strong>where the boundary of a database transaction actually ends</strong>.</p><p>In Rails, this code:</p><pre>User.transaction do # ... end</pre><p>can look like an atomic business operation.</p><p>But if that block interacts with systems outside the database, the operation is no longer truly atomic.</p><p>That distinction becomes especially important in applications that integrate with:</p><ul><li>payment providers</li><li>CRMs</li><li>messaging platforms</li><li>email providers</li><li>analytics systems</li><li>background job queues</li><li>external APIs</li></ul><p>A rollback can undo your database state.</p><p>It cannot necessarily undo what another system has already observed.</p><h3>The bigger lesson</h3><p>A transaction is not the same thing as a distributed transaction.</p><p>This:</p><pre>User.transaction do<br>  user = User.create!<br>  ExternalAPI.create_user(user)<br>end</pre><p>contains two different worlds:</p><pre>        Database<br>           │<br>       transaction<br>           │<br>        rollback<br>           │<br>           X<br>           <br>       External API<br>           │<br>       request sent<br>           │<br>       cannot magically<br>       be rolled back</pre><p>Once you recognize that boundary, you can make a deliberate architectural decision about what should happen before commit, after commit, or through a more reliable event-driven workflow.</p><p>That’s the problem TransactionGuard is designed to make visible.</p><h3>Try TransactionGuard</h3><p>If you’re working on a Rails application with external integrations, you can try the gem here:</p><p><strong>GitHub:</strong> <a href="https://github.com/yashika279/transaction%5C_guard">https://github.com/yashika279/transaction\_guard</a></p><p>I’d especially like feedback on:</p><ul><li>additional external side effects worth detecting</li><li>integrations with other HTTP clients</li><li>background job adapters</li><li>false positives</li><li>better reporting</li><li>Rails version compatibility</li></ul><p>If you’ve ever had a transaction roll back while an email, API call, or background job had already escaped the transaction, this is exactly the kind of problem TransactionGuard is trying to catch earlier.</p><p><em>Originally published at </em><a href="https://railswithyashika.hashnode.dev/your-rails-transaction-rolled-back-what-happened-to-the-api-call-email-or-job"><em>https://railswithyashika.hashnode.dev</em></a><em> on September 22, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=408c6ae49bbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Assistant Forgot You: Understanding Memory, Sessions, and OmniMemory]]></title>
            <link>https://medium.com/@yashika270499/your-ai-assistant-forgot-you-understanding-memory-sessions-and-omnimemory-ceca2a00db6d?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceca2a00db6d</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 11:00:34 GMT</pubDate>
            <atom:updated>2026-09-16T11:00:34.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>OmniMemory Explained: Giving AI Coding Agents Persistent, Git-Aware Memory</h3><blockquote><strong><em>Note:</em></strong><em> AI coding tools are evolving extremely quickly. OmniMemory is an actively developed open-source project, so commands, supported integrations, architecture, and behavior may change over time. This article is intended to create awareness and explain the ideas behind OmniMemory. Before installing or using it in a real project, always check the latest </em><a href="https://github.com/SinghAbhinav04/Omni-Memory"><em>OmniMemory repository</em></a><em> and documentation.</em></blockquote><h3>Introduction</h3><p>AI coding assistants have become an important part of modern software development.</p><p>Tools such as Claude Code, Cursor, OpenCode, Windsurf, and other AI-powered development environments can understand your repository, modify files, run commands, write tests, and help you debug complicated problems.</p><p>But there is one problem that almost every AI coding workflow eventually runs into:</p><p><strong>The AI forgets.</strong></p><p>You may spend two hours explaining your architecture to an AI agent.</p><p>You might explain:</p><ul><li>why a particular service exists</li><li>why a database query is written in a strange way</li><li>why a certain method must not be changed</li><li>why a particular workaround was introduced</li><li>how two services communicate</li><li>why a particular branch is implementing a specific approach</li></ul><p>Then the session ends.</p><p>Later, you start another session and the AI doesn’t necessarily remember those decisions.</p><p>You explain everything again.</p><p>And sometimes, instead of asking, the AI simply guesses.</p><p>This is the problem <strong>OmniMemory</strong> is designed to address.</p><p>OmniMemory describes itself as a <strong>memory and context layer for coding agents</strong> that is persistent, branch-aware, Git-anchored, and local.</p><p>But what does that actually mean?</p><p>Let’s break it down.</p><h3>The Problem: AI Coding Agents Have Short-Term Context</h3><p>Before understanding OmniMemory, let’s understand the problem it is trying to solve.</p><p>Imagine you are working on a Rails application.</p><p>Your project contains:</p><pre>app/<br>├── models/<br>├── services/<br>├── controllers/<br>├── jobs/<br>└── policies/</pre><p>You ask your AI coding agent:</p><blockquote><em>“Why are we using this service instead of calling Stripe directly from the controller?”</em></blockquote><p>You explain:</p><blockquote><em>“We originally had the Stripe call inside the controller, but webhook retries caused duplicate records. We moved it into this service because the service handles idempotency.”</em></blockquote><p>The AI now understands the reason.</p><p>You continue working.</p><p>You make several changes.</p><p>Then the session ends.</p><p>The next day you start another conversation:</p><blockquote><em>“Update the Stripe integration.”</em></blockquote><p>The AI may inspect the code, but the <strong>reason behind the architecture</strong> might not be obvious from the code itself.</p><p>This is an important distinction:</p><h3>Code tells you WHAT.</h3><h3>Documentation may tell you HOW.</h3><h3>Memory can tell you WHY.</h3><p>That “why” is often the most valuable information.</p><h3>Why Markdown Files Are Not Always Enough</h3><p>A common solution is to create a file such as:</p><pre>MEMORY.md</pre><p>and manually write:</p><pre># Project Notes</pre><pre>- Stripe calls must go through PaymentService.<br>- Never call Stripe directly from controllers.<br>- Orders use pessimistic locking.<br>- Redis is used for distributed locks.</pre><p>This works.</p><p>But it creates another problem.</p><p>The AI has to receive the entire document or search through it.</p><p>If the file becomes large, injecting everything into every prompt can increase context size and token usage.</p><p>You might end up with:</p><pre>Prompt<br>  ↓<br>Entire MEMORY.md<br>  ↓<br>AI<br>  ↓<br>Actual question</pre><p>That’s not ideal.</p><p>OmniMemory takes a different approach.</p><p>Instead of simply pushing all memory into every prompt, it maintains a local memory store and retrieves relevant information based on the current task. The project describes this as context-aware retrieval using a BM25F ranker, code-graph proximity, and citation feedback.</p><h3>What Is OmniMemory?</h3><p>At a high level:</p><p><strong>OmniMemory is a persistent memory layer for AI coding agents.</strong></p><p>It is designed to remember things such as:</p><ul><li>decisions</li><li>facts</li><li>request/data flows</li><li>implementation gotchas</li><li>project-specific knowledge</li><li>architectural reasoning</li></ul><p>The memory is not simply a collection of notes.</p><p>The project anchors memories to the codebase and Git history.</p><p>That gives the memory additional context about whether the information is still relevant.</p><h3>The Four Important Ideas Behind OmniMemory</h3><p>There are four concepts that are particularly important to understand.</p><h3>1. Persistent Memory</h3><p>The memory survives across AI sessions.</p><p>Instead of:</p><pre>Session 1<br>   ↓<br>AI learns architecture<br>   ↓<br>Session ends<br>   ↓<br>Memory disappears</pre><p>you can have:</p><pre>Session 1<br>   ↓<br>AI learns architecture<br>   ↓<br>Memory stored<br>   ↓<br>Session 2<br>   ↓<br>Relevant memory retrieved</pre><p>This is the fundamental idea behind the project.</p><h3>2. Branch-Aware Memory</h3><p>This is one of the more interesting parts of OmniMemory.</p><p>Software projects are rarely developed on only one branch.</p><p>You might have:</p><pre>main<br> ├── feature/payment-refactor<br> ├── feature/search<br> └── bugfix/checkout</pre><p>Each branch may introduce different decisions.</p><p>For example:</p><pre>main<br>  |<br>  +--- feature/payment-refactor<br>  |       |<br>  |       +--- PaymentService changed<br>  |<br>  +--- feature/search<br>          |<br>          +--- Elasticsearch introduced</pre><p>A memory created while working on feature/search may not make sense when working on feature/payment-refactor.</p><p>OmniMemory therefore scopes memory around Git branches and tracks branch information. The repository describes merged branch memories as rolling into the base branch.</p><p>This is significantly more useful than treating the entire repository as one flat memory store.</p><h3>3. Git-Anchored Memory</h3><p>This is another major concept.</p><p>Imagine the AI remembers:</p><blockquote><em>“The checkout calculation happens in </em><em>CheckoutService.&quot;</em></blockquote><p>But six months later you completely rewrite the checkout architecture.</p><p>If the AI blindly trusts the old memory, it can give you incorrect information.</p><p>That’s dangerous.</p><p>OmniMemory attempts to connect memory to the code it describes and check whether the relevant code has changed.</p><p>Its current implementation uses a code graph and Git information to perform symbol-level staleness checks. When tree-sitter isn’t available, it can fall back to file-level checking.</p><p>Conceptually:</p><pre>Memory<br>  |<br>  +--- Code symbol<br>          |<br>          +--- Git history</pre><p>If the relevant symbol changes, the memory can be identified as potentially stale.</p><p>This is much more useful than simply storing:</p><pre>created_at: 2026-08-01</pre><p>because time alone doesn’t tell you whether the information is still correct.</p><h3>4. Local-First Architecture</h3><p>OmniMemory is designed to operate locally.</p><p>The repository describes its core as using Python’s standard library and SQLite, with no API key required for the core functionality.</p><p>The architecture is essentially:</p><pre>Your Repository<br>      |<br>      ↓<br>OmniMemory<br>      |<br>      ├── SQLite<br>      ├── Git information<br>      ├── Code graph<br>      └── Memory</pre><p>The repository also describes the system as local-first, with no cloud memory store required for its core operation.</p><p>This can be particularly attractive for developers working with private repositories.</p><h3>How OmniMemory Works</h3><p>The repository summarizes its architecture as:</p><pre>CAPTURE<br>   ↓<br>STORE<br>   ↓<br>RANK + INJECT + ENFORCE<br>   ↓<br>CHECK<br>   ↓<br>VISUALIZE</pre><p>Let’s understand each stage.</p><h3>Step 1: Capture</h3><p>OmniMemory captures information from coding sessions.</p><p>The project describes deterministic harness events such as:</p><pre>UserPromptSubmit<br>        ↓<br>     Inject<br>        ↓<br>   AI session<br>        ↓<br>   SessionEnd<br>        ↓<br>     Capture</pre><p>This is important because memory capture isn’t supposed to depend entirely on the AI remembering to save something.</p><h3>Step 2: Store</h3><p>The captured information is stored locally.</p><p>The repository uses SQLite for its core storage.</p><p>Conceptually:</p><pre>AI Session<br>    |<br>    ↓<br>Memory<br>    |<br>    ↓<br>SQLite</pre><p>Each memory can contain contextual information about the project and branch.</p><h3>Step 3: Retrieve Relevant Memory</h3><p>This is where the system becomes more interesting.</p><p>Suppose you ask:</p><blockquote><em>“Why does this service use Redis?”</em></blockquote><p>You don’t want every memory in your project.</p><p>You want memories related to:</p><pre>Redis<br>Service<br>Current file<br>Current symbols<br>Architecture</pre><p>OmniMemory uses a BM25F-based ranking system with weighting across symbols, files, and prose. It also considers code-graph proximity and whether the agent has previously cited a memory.</p><p>So conceptually:</p><pre>Your question<br>      |<br>      ↓<br>Memory search<br>      |<br>      ├── keyword relevance<br>      ├── symbol relevance<br>      ├── file relevance<br>      ├── code proximity<br>      └── previous citations<br>      |<br>      ↓<br>Relevant memories</pre><p>The goal is to provide the AI with <strong>the useful memory</strong>, rather than everything the system knows.</p><h3>BM25F Instead of Embeddings</h3><p>This is worth highlighting.</p><p>Many modern AI retrieval systems immediately use vector embeddings.</p><p>OmniMemory’s README instead describes its retrieval system around <strong>BM25F</strong> and explicitly notes that it doesn’t require embeddings or an API key for this retrieval.</p><p>BM25 is a traditional information-retrieval technique based largely on lexical relevance.</p><p>The simplified idea is:</p><pre>Query:<br>&quot;Redis locking checkout&quot;</pre><pre>        ↓</pre><pre>Search memories</pre><pre>        ↓</pre><pre>Rank memories containing relevant<br>terms and fields</pre><pre>        ↓</pre><pre>Return the most relevant memories</pre><p>This can be particularly useful for developer knowledge because code contains many exact identifiers:</p><pre>CheckoutService<br>RedisLock<br>PaymentService<br>Order</pre><p>Exact symbol and file matching can be highly valuable.</p><h3>Step 4: Inject Memory Into the AI Context</h3><p>Once relevant memory is found, OmniMemory can inject it into the AI’s context.</p><p>The project describes a VERIFIED PROJECT MEMORY block and an enforcement mechanism where the agent is expected to cite memory it uses or acknowledge when information isn&#39;t available in memory.</p><p>The conceptual flow becomes:</p><pre>Developer question<br>       ↓<br>OmniMemory searches<br>       ↓<br>Relevant memory<br>       ↓<br>AI receives memory<br>       ↓<br>AI answers</pre><h3>Why “Enforced Memory” Matters</h3><p>Imagine the AI doesn’t know why a piece of code exists.</p><p>A dangerous AI behavior is:</p><blockquote><em>“I think this was added because…”</em></blockquote><p>That is a guess.</p><p>OmniMemory’s approach attempts to distinguish between remembered information and information that isn’t available in its memory.</p><p>This encourages a safer behavior:</p><pre>Known from memory<br>        ↓<br>Cite it</pre><pre>Not known<br>        ↓<br>Say it isn&#39;t in memory</pre><p>The repository specifically describes this as making the agent cite the memory it used or admit that something isn’t in memory rather than inventing it.</p><p>That distinction is extremely important for AI-assisted software development.</p><h3>Step 5: Check Whether Memory Is Stale</h3><p>Imagine we have:</p><pre>Memory:</pre><pre>&quot;PaymentService handles Stripe payment creation.&quot;</pre><p>Then we refactor the application.</p><p>Now:</p><pre>PaymentProcessor</pre><p>handles the payment instead.</p><p>The old memory should no longer be trusted.</p><p>OmniMemory’s check command can compare memory anchors against the current Git/code graph state and flag stale memories.</p><p>The project describes this at the symbol level when the code graph is available.</p><p>That’s more precise than simply saying:</p><blockquote><em>“The file changed, therefore the memory is invalid.”</em></blockquote><h3>Step 6: Clean Up Bad Memory</h3><p>Memory can become dangerous if everything is stored forever.</p><p>Imagine your AI remembers:</p><pre>&quot;We use Redis for checkout locking.&quot;</pre><p>Then you remove Redis completely.</p><p>If that memory remains forever, future AI sessions may receive incorrect information.</p><p>OmniMemory includes memory hygiene mechanisms intended to quarantine abandoned-branch and long-stale/uncited memories, while keeping hard deletion human-gated.</p><p>This creates an important lifecycle:</p><pre>Memory created<br>      ↓<br>Memory used<br>      ↓<br>Memory verified<br>      ↓<br>Code changes<br>      ↓<br>Memory becomes stale<br>      ↓<br>Memory quarantined</pre><h3>The Code Graph</h3><p>OmniMemory also builds a code graph.</p><p>The repository currently describes tree-sitter support for Python, JavaScript, and TypeScript, with a standard-library ast fallback for Python.</p><p>A simplified graph could look like:</p><pre>OrderController<br>       |<br>       ↓<br>OrderService<br>       |<br>       ↓<br>PaymentService<br>       |<br>       ↓<br>StripeClient</pre><p>Now imagine a memory is attached to:</p><pre>PaymentService</pre><p>If you’re currently editing:</p><pre>OrderService</pre><p>the graph can help determine that the PaymentService-related memory is nearby in the code relationship.</p><p>This provides another signal for memory retrieval.</p><h3>The Local Dashboard</h3><p>OmniMemory also provides a local UI.</p><p>The repository says omni-memory ui can be used to browse:</p><ul><li>memory</li><li>documentation</li><li>knowledge graph</li><li>repository graph</li><li>branch graph</li></ul><p>So instead of treating memory as a black box, you can inspect what the system has stored.</p><p>That’s useful because developers should be able to answer:</p><blockquote><em>“What does my AI actually remember about this project?”</em></blockquote><h3>Installation</h3><p>The repository currently recommends installing the CLI through pip:</p><pre>pip install omni-memory-agent</pre><p>For Claude Code, the project also provides a plugin installation approach. The current README shows:</p><pre>/plugin marketplace add SinghAbhinav04/Omni-Memory<br>/plugin install omni-memory@singhabhinav</pre><p>Because these commands may change as the project develops, <strong>always check the repository before following installation instructions from this article.</strong></p><h3>The Most Important Commands</h3><p>After installation, the project currently distinguishes between two commands that are easy to confuse:</p><pre>omni-memory build</pre><p>and:</p><pre>omni-memory bind</pre><p>They are not the same.</p><h3>build</h3><p>build creates the memory and documentation from your repository.</p><p>The project describes it as capturing decisions, flows, and gotchas, building the code graph, and generating files such as:</p><pre>MEMORY.md<br>api-map.md<br>linkup.md</pre><h3>bind</h3><p>bind connects OmniMemory to your development environment.</p><p>It installs session hooks and writes the cross-IDE AGENTS.md.</p><p>It does <strong>not</strong> create the initial memory itself.</p><h3>Recommended Initial Workflow</h3><p>The repository currently suggests this general sequence:</p><pre>pip install omni-memory-agent</pre><pre>omni-memory build</pre><pre>omni-memory bind</pre><pre>omni-memory ui</pre><pre>omni-memory doctor</pre><p>The roles are:</p><pre>build<br> ↓<br>Create memory + docs</pre><pre>bind<br> ↓<br>Connect memory to IDE</pre><pre>ui<br> ↓<br>Inspect memory and graphs</pre><pre>doctor<br> ↓<br>Check setup</pre><p>The UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*PJBKor2LhE9EoUNv.png" /></figure><p>Memory Graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ssirntfaSoDlScuI.png" /></figure><h3>Does build Require an AI Model?</h3><p>There is an important nuance here.</p><p>The project says build can use an agent/LLM to analyze the repository.</p><p>You can run it inside an AI IDE, or configure a model key.</p><p>The repository currently lists model-key support for Gemini, Anthropic, and OpenAI. Without an AI/model path, it can still build the code graph and heuristic documentation, but it won’t generate AI-written facts.</p><p>So:</p><pre>OmniMemory core<br>      |<br>      ├── Local memory<br>      ├── SQLite<br>      ├── Git<br>      └── Code graph</pre><pre>Optional AI analysis<br>      |<br>      ├── Gemini<br>      ├── Anthropic<br>      └── OpenAI</pre><p>This distinction is important.</p><p><strong>OmniMemory itself isn’t the language model.</strong></p><h3>Useful Commands</h3><p>The current CLI includes commands for several different workflows.</p><h3>Memory</h3><pre>omni-memory recall &quot;payment retry logic&quot;</pre><p>Searches memory.</p><pre>omni-memory remember &quot;PaymentService must be idempotent&quot;</pre><p>Adds a memory manually.</p><pre>omni-memory forget &lt;id&gt;</pre><p>Removes or manages a memory entry.</p><h3>Branches</h3><pre>omni-memory branches</pre><p>Allows you to inspect Git topology and branch-specific memory.</p><h3>Keeping Memory Fresh</h3><pre>omni-memory map</pre><p>Rebuilds the knowledge/code graph.</p><pre>omni-memory check</pre><p>Checks memory anchors against the codebase.</p><pre>omni-memory gc --dry-run</pre><p>Previews memory cleanup.</p><p>The current project also provides a usage command for inspecting the memory footprint per prompt.</p><h3>What About Token Usage?</h3><p>This is an interesting question for developers using paid AI models.</p><p>If you inject an enormous MEMORY.md into every prompt:</p><pre>Prompt<br>+<br>50,000 tokens of project memory<br>+<br>Your actual question</pre><p>you are potentially wasting context.</p><p>OmniMemory instead tries to retrieve only relevant memory.</p><p>Conceptually:</p><pre>10,000 memories</pre><pre>        ↓</pre><pre>Relevant retrieval</pre><pre>        ↓</pre><pre>5 useful memories</pre><pre>        ↓</pre><pre>AI prompt</pre><p>The project’s retrieval and usage tooling are designed around keeping the relevant memory footprint under control.</p><p>However, this should <strong>not</strong> be interpreted as a guaranteed percentage reduction in your AI bill.</p><p>Actual token consumption depends on:</p><ul><li>the AI model</li><li>the coding agent</li><li>prompt size</li><li>repository size</li><li>retrieved memory</li><li>task complexity</li></ul><h3>OmniMemory vs a Simple MEMORY.md</h3><p>Let’s compare the two approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*flLozh74HpZILT71C2_VhA.png" /></figure><p>The important point isn’t that Markdown is bad.</p><p>Markdown is excellent for:</p><ul><li>human documentation</li><li>project conventions</li><li>onboarding</li><li>architecture notes</li></ul><p>OmniMemory is trying to solve a different problem:</p><p><strong>machine-oriented persistent context for AI coding agents.</strong></p><h3>OmniMemory vs RAG</h3><p>At a high level, OmniMemory may remind you of Retrieval-Augmented Generation (RAG).</p><p>Traditional RAG looks something like:</p><pre>Documents<br>   ↓<br>Chunking<br>   ↓<br>Embeddings<br>   ↓<br>Vector database<br>   ↓<br>Similarity search<br>   ↓<br>LLM</pre><p>OmniMemory takes a different approach for coding environments.</p><p>It emphasizes:</p><pre>Memory<br>+<br>Git<br>+<br>Code symbols<br>+<br>Branch information<br>+<br>Lexical ranking<br>+<br>Code graph<br>+<br>Agent citations</pre><p>The goal is not simply:</p><blockquote><em>“Find text that looks similar.”</em></blockquote><p>It is closer to:</p><blockquote><em>“Find project knowledge that is relevant to what I’m currently changing.”</em></blockquote><p>That distinction matters for software repositories.</p><h3>A Real-World Rails Example</h3><p>Imagine a Rails application with:</p><pre>Order<br>Payment<br>Refund<br>Stripe<br>Sidekiq<br>Redis</pre><p>You have an architectural rule:</p><pre>Payment processing must be idempotent.</pre><p>But the reason isn’t obvious from the code.</p><p>The reason is:</p><pre>Stripe webhook<br>      ↓<br>Retry<br>      ↓<br>Same payment event<br>      ↓<br>Potential duplicate payment</pre><p>So the team introduced an idempotency mechanism.</p><p>Six months later, another developer asks an AI:</p><blockquote><em>“Can I remove this Redis lock?”</em></blockquote><p>Without project memory, the AI might see the lock as unnecessary complexity.</p><p>With relevant project memory, the agent can retrieve:</p><pre>Payment processing requires idempotency<br>because Stripe webhook retries can produce<br>duplicate processing.</pre><p>Now the AI has architectural context.</p><p>This is where persistent project memory becomes useful.</p><h3>Another Example: Open-Source Contributions</h3><p>This is especially interesting for open-source projects.</p><p>Imagine you contribute to a large Rails repository.</p><p>During your first contribution, you learn:</p><pre>Do not modify this service directly.<br>The event data is generated from YAML.<br>Run validate:all before submitting a PR.</pre><p>A normal AI conversation might forget these details later.</p><p>Persistent project memory can help preserve this project-specific knowledge across sessions.</p><p>For developers contributing to large open-source repositories, this can be extremely useful.</p><h3>Who Should Consider Using OmniMemory?</h3><p>OmniMemory is particularly interesting if you:</p><h3>Work on large repositories</h3><p>Large repositories have more architectural context.</p><h3>Work with AI coding agents every day</h3><p>The more you rely on AI, the more useful persistent context can become.</p><h3>Frequently switch branches</h3><p>Branch-aware memory can prevent unrelated context from bleeding across branches.</p><h3>Maintain long-running projects</h3><p>Long-lived projects accumulate decisions and historical knowledge.</p><h3>Work on open source</h3><p>Project-specific conventions can take significant time to learn.</p><h3>Frequently start new AI sessions</h3><p>Persistent memory can reduce the need to repeatedly explain the same project context.</p><h3>Who Probably Doesn’t Need It?</h3><p>You probably don’t need a sophisticated memory layer for:</p><pre>hello_world.py</pre><p>or:</p><pre>one-off script</pre><p>or:</p><pre>small coding exercise</pre><p>If your project is tiny and the AI can understand everything from the repository in seconds, additional memory infrastructure may provide little benefit.</p><h3>Potential Concerns</h3><p>No tool should be adopted simply because it sounds interesting.</p><p>There are some things developers should consider.</p><h3>1. Memory Can Be Wrong</h3><p>Persistent memory is only useful if it remains accurate.</p><p>That’s why Git anchoring and stale-memory detection are important.</p><p>But you should still review what the system remembers.</p><h3>2. AI-Generated Memory Needs Review</h3><p>If an AI creates a memory about your architecture, that memory can itself be wrong.</p><p>A persistent wrong answer can be worse than no memory.</p><p>Always treat AI-generated project knowledge as something to verify.</p><h3>3. The Project Is Actively Evolving</h3><p>The repository is under active development.</p><p>Its current README lists several capabilities as implemented and others as roadmap items.</p><p>Therefore, don’t treat this article as a frozen specification.</p><p>The official repository is the source of truth for current behavior.</p><h3>The Bigger Idea: AI Needs Long-Term Project Context</h3><p>The interesting thing about OmniMemory isn’t just the CLI.</p><p>The bigger idea is:</p><blockquote><strong><em>AI coding agents need a memory system that understands software projects, not just text.</em></strong></blockquote><p>A software project contains relationships:</p><pre>File<br> ↓<br>Class<br> ↓<br>Method<br> ↓<br>Database<br> ↓<br>Service<br> ↓<br>External API</pre><p>It also contains history:</p><pre>Commit<br> ↓<br>Refactor<br> ↓<br>Decision<br> ↓<br>New architecture</pre><p>And it contains branches:</p><pre>main<br> ↓<br>feature<br> ↓<br>experiments<br> ↓<br>merge</pre><p>A useful coding memory system needs to understand these relationships.</p><p>That is what makes OmniMemory interesting.</p><h3>OmniMemory’s Architecture in One Diagram</h3><p>At a high level, you can think about it like this:</p><pre>┌───────────────────┐<br>                         │   Developer       │<br>                         └─────────┬─────────┘<br>                                   │<br>                                   ▼<br>                         ┌───────────────────┐<br>                         │   AI Coding Agent │<br>                         └─────────┬─────────┘<br>                                   │<br>                         ┌─────────▼─────────┐<br>                         │    OmniMemory     │<br>                         └─────────┬─────────┘<br>                                   │<br>             ┌─────────────────────┼─────────────────────┐<br>             │                     │                     │<br>             ▼                     ▼                     ▼<br>        ┌─────────┐          ┌──────────┐          ┌──────────┐<br>        │ SQLite  │          │   Git    │          │Code Graph│<br>        └─────────┘          └──────────┘          └──────────┘<br>             │                     │                     │<br>             └─────────────────────┼─────────────────────┘<br>                                   │<br>                                   ▼<br>                         ┌───────────────────┐<br>                         │ Relevant Memory   │<br>                         └─────────┬─────────┘<br>                                   │<br>                                   ▼<br>                         ┌───────────────────┐<br>                         │ AI Context        │<br>                         └───────────────────┘</pre><p>This is the key concept to remember.</p><p>If you ran these today:</p><p>pip install omni-memory-agent</p><p>omni-memory build omni-memory bind omni-memory ui omni-memory doctor</p><p>then you should not need to run all of them again when your AI session ends or you open a new VS Code window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*nyDkbzt3OfofG-W5.png" /></figure><p>You should normally just open your project and start using your AI assistant.</p><p>The important part is that you ran:</p><p>omni-memory bind</p><p>That is the step that connects the generated memory/context to your development environment.</p><p>When should you run omni-memory build again?</p><p>This is the one you’ll potentially use regularly.</p><p>For example, today you have:</p><p>Project ├── Rails app ├── locking implementation ├── tests └── architecture</p><p>You work for a few days and add significant new things:</p><p>Project ├── Rails app ├── locking implementation ├── tests ├── new payment system ├── new background-job architecture └── new API integration</p><p>Then run:</p><p>omni-memory build</p><p>to update the memory/documentation/code graph based on the newer state of your repository.</p><p>So think of it as:</p><p>Initial setup ↓ pip install ↓ omni-memory build ↓ omni-memory bind ↓ Use your AI normally ↓ New session ↓ Use AI normally ↓ Major project changes? ↓ omni-memory build One thing I&#39;d recommend</p><p>After you’ve closed/reopened VS Code, run:</p><p>omni-memory doctor</p><p>once just to verify that everything is still connected.</p><p>If it says the setup is healthy, you don’t need to rebuild or bind again.</p><p>Also, omni-memory ui is not what makes the AI remember things; it’s primarily for browsing/inspecting the generated memory, docs, and code graph.</p><p>If you want, I can also explain exactly what Omni-Memory is storing, where that memory lives, and how your AI actually gets that memory when you start a new chat/session.</p><h3>Final Thoughts</h3><p>AI coding assistants are becoming increasingly capable.</p><p>But intelligence isn’t the only problem.</p><p><strong>Context is the problem.</strong></p><p>An AI can be extremely capable and still make a bad decision if it doesn’t know why your project was designed the way it was.</p><p>OmniMemory approaches this problem by combining:</p><ul><li>persistent memory</li><li>Git provenance</li><li>branch awareness</li><li>code relationships</li><li>relevance ranking</li><li>stale-memory detection</li><li>memory hygiene</li><li>local storage</li><li>AI-agent integration</li></ul><p>The most interesting part is that it doesn’t simply try to give the AI <strong>more context</strong>.</p><p>It tries to give the AI <strong>the right context at the right time</strong>.</p><p>That is a much more interesting problem.</p><p>And as AI coding agents become a larger part of everyday software development, persistent project memory could become an important part of the developer tooling ecosystem.</p><p>If you use Claude Code, Cursor, OpenCode, Windsurf, or another AI coding workflow, OmniMemory is worth understanding — even if you don’t immediately adopt it.</p><p>The project is actively evolving, so check the official repository for the latest installation instructions, supported integrations, commands, and roadmap before using it in your workflow.</p><p><strong>Repository:</strong> <a href="https://github.com/SinghAbhinav04/Omni-Memory">https://github.com/SinghAbhinav04/Omni-Memory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceca2a00db6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pessimistic Locking in Rails — Preventing Race Conditions in Production]]></title>
            <link>https://medium.com/@yashika270499/pessimistic-locking-in-rails-preventing-race-conditions-in-production-fc6027a1ae19?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6027a1ae19</guid>
            <category><![CDATA[locking]]></category>
            <category><![CDATA[optimistic-locking]]></category>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 10:48:06 GMT</pubDate>
            <atom:updated>2026-09-16T10:48:06.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the previous article, we learned why databases need locking and how PostgreSQL uses <strong>MVCC (Multi-Version Concurrency Control)</strong> to allow multiple transactions to work simultaneously.</p><p>However, MVCC alone cannot prevent every concurrency issue.</p><p>Imagine an e-commerce application where there is only <strong>one product left in stock</strong>.</p><p>Two customers click <strong>“Buy Now”</strong> at almost the same time.</p><p>Without proper locking, both requests may purchase the same product.</p><p>This is where <strong>Pessimistic Locking</strong> becomes essential.</p><p>In this article, we’ll understand how pessimistic locking works in PostgreSQL and how Rails makes it easy to use in production applications.</p><h3>What is Pessimistic Locking?</h3><p><strong>Definition</strong></p><p>Pessimistic locking is a strategy where a transaction <strong>locks a row before modifying it</strong>, preventing other transactions from changing that row until the lock is released.</p><p>In simple words:</p><blockquote><em>“I’m assuming someone else might modify this row, so I’m locking it first.”</em></blockquote><p>Unlike optimistic locking, pessimistic locking assumes conflicts are likely and prevents them before they happen.</p><h3>Why Do We Need Pessimistic Locking?</h3><p>Consider a banking application.</p><p>Current balance:</p><pre>$100</pre><p>Two requests arrive simultaneously.</p><p>Transaction A:</p><pre>account.balance -= 80<br>account.save!</pre><p>Transaction B:</p><pre>account.balance -= 50<br>account.save!</pre><p>Without locking:</p><blockquote><em>Balance = $100</em></blockquote><blockquote><em>↓</em></blockquote><blockquote><em>Transaction A reads $100</em></blockquote><blockquote><em>↓</em></blockquote><blockquote><em>Transaction B reads $100</em></blockquote><blockquote><em>↓</em></blockquote><blockquote><em>A saves $20</em></blockquote><blockquote><em>↓</em></blockquote><blockquote><em>B saves $50</em></blockquote><blockquote><em>↓</em></blockquote><blockquote><em>Final Balance = $50 ❌</em></blockquote><p>Expected:</p><pre>$100 - $80 - $50 = -$30</pre><p>Actual:</p><pre>$50</pre><p>This is called a <strong>Lost Update</strong>.</p><h3>How PostgreSQL Solves This</h3><p>PostgreSQL provides</p><pre>SELECT ... FOR UPDATE;</pre><p>When a transaction executes:</p><pre>SELECT *<br>FROM accounts<br>WHERE id = 1<br>FOR UPDATE;</pre><p>that row becomes locked.</p><p>Any other transaction trying to update the same row must wait until the first transaction commits or rolls back.</p><h3>Rails Pessimistic Locking</h3><p>Rails exposes PostgreSQL row locking through several APIs.</p><h3>1. lock</h3><p>Example:</p><pre>Account.transaction do<br>  account = Account.lock.find(params[:id])</pre><pre>  account.balance -= 80</pre><pre>  account.save!<br>end</pre><p>Generated SQL:</p><pre>BEGIN;</pre><pre>SELECT *<br>FROM accounts<br>WHERE id = 1<br>FOR UPDATE;</pre><pre>UPDATE accounts<br>SET balance = 20<br>WHERE id = 1;</pre><pre>COMMIT;</pre><p>Notice:</p><pre>FOR UPDATE</pre><p>This is the important part.</p><h3>Timeline</h3><p>Without locking</p><pre>Transaction A          Transaction B</pre><pre>Read balance=100</pre><pre>                      Read balance=100</pre><pre>Update balance=20</pre><pre>                      Update balance=50</pre><pre>Final = 50 ❌</pre><p>With locking</p><pre>Transaction A          Transaction B</pre><pre>Lock row</pre><pre>Read balance=100</pre><pre>Update balance=20</pre><pre>Commit</pre><pre>                      Wait...</pre><pre>                      Lock acquired</pre><pre>                      Read balance=20</pre><pre>                      Update balance=-30</pre><pre>Commit<br>Final = -30 ✅</pre><h3>2. lock!</h3><p>If you already have the record:</p><pre>account = Account.find(1)</pre><pre>account.lock!</pre><pre>account.balance -= 50</pre><pre>account.save!</pre><p>Instead of querying again, Rails locks the existing record.</p><h3>3. with_lock</h3><p>This is the cleanest API.</p><pre>account = Account.find(1)</pre><pre>account.with_lock do<br>  account.balance -= 50</pre><pre>  account.save!<br>end</pre><p>Rails automatically:</p><ul><li>starts a transaction</li><li>locks the row</li><li>executes the block</li><li>commits</li><li>releases the lock</li></ul><p>Equivalent SQL:</p><pre>BEGIN;</pre><pre>SELECT *<br>FROM accounts<br>WHERE id = 1<br>FOR UPDATE;</pre><pre>UPDATE accounts...</pre><pre>COMMIT;</pre><h3>Why with_lock is Preferred</h3><p>Instead of:</p><pre>Account.transaction do<br>  account = Account.lock.find(id)<br>end</pre><p>You simply write:</p><pre>account.with_lock do<br>  ...<br>end</pre><p>Cleaner.</p><p>Safer.</p><p>More readable.</p><h3>Locking Multiple Rows</h3><p>Example:</p><pre>Product.transaction do<br>  products = Product.lock.where(category_id: 1)<br>  products.each do |product|<br>      product.update!(price: product.price * 1.1)<br>   end<br>end</pre><p>All selected rows remain locked until the transaction completes.</p><h3>NOWAIT</h3><p>Sometimes you don’t want to wait.</p><p>Instead:</p><pre>Product.lock(&quot;FOR UPDATE NOWAIT&quot;)</pre><p>Generated SQL:</p><pre>FOR UPDATE NOWAIT</pre><p>If another transaction already owns the lock:</p><p>Instead of waiting,</p><p>PostgreSQL immediately raises an error.</p><p>Useful for:</p><ul><li>payment processing</li><li>reservation systems</li><li>inventory</li></ul><h3>SKIP LOCKED</h3><p>Another useful option.</p><pre>Job.lock(&quot;FOR UPDATE SKIP LOCKED&quot;)</pre><p>Instead of waiting,</p><p>locked rows are skipped.</p><p>Example:</p><pre>Job 1 Locked</pre><pre>Job 2 Free</pre><pre>Job 3 Locked</pre><pre>Job 4 Free</pre><p>Worker gets:</p><pre>Job 2</pre><pre>Job 4</pre><p>Very common in:</p><ul><li>Sidekiq alternatives</li><li>queue systems</li><li>job schedulers</li></ul><h3>Real Production Example 1</h3><h3>Inventory Reservation</h3><p>Product</p><pre>Inventory = 1</pre><p>Safe implementation</p><pre>Product.transaction do<br>  product = Product.lock.find(id)<br>raise &quot;Out of stock&quot; if product.inventory.zero?<br>  product.inventory -= 1<br>  product.save!<br>end</pre><p>No two users can purchase the last item simultaneously.</p><h3>Real Production Example 2</h3><h3>Hotel Booking</h3><p>Room:</p><pre>Available</pre><p>Without locking:</p><p>Two guests reserve the same room.</p><p>With locking:</p><p>Guest A locks the room.</p><p>Guest B waits.</p><p>Guest A confirms booking.</p><p>Guest B now sees:</p><pre>Room unavailable</pre><h3>Real Production Example 3</h3><h3>Wallet Transfer</h3><pre>Wallet.transaction do<br>  wallet = Wallet.lock.find(id)<br>  wallet.balance -= amount<br>  wallet.save!<br>end</pre><p>Prevents inconsistent balances.</p><h3>Lock Duration</h3><p>A common misconception:</p><p>People think locks remain forever.</p><p>Reality:</p><pre>BEGIN</pre><pre>↓</pre><pre>Lock row</pre><pre>↓</pre><pre>Update</pre><pre>↓</pre><pre>COMMIT</pre><pre>↓</pre><pre>Lock released</pre><p>Locks exist <strong>only during the transaction</strong>.</p><h3>Things to Avoid</h3><h3>Long Transactions</h3><p>Bad</p><pre>User.transaction do<br>  user.lock!<br>  sleep 30<br>  user.update!<br>end</pre><p>The row remains locked for 30 seconds.</p><p>Other users wait.</p><h3>External API Calls Inside Transactions</h3><p>Avoid:</p><pre>User.transaction do<br>  user.lock!<br>  Stripe.charge(...)<br>  user.update!<br>end</pre><pre>Network calls increase lock duration.</pre><p>Instead:</p><pre>Stripe.charge(...)</pre><pre>User.transaction do<br>  user.lock!</pre><pre>  user.update!<br>end</pre><p>Keep transactions as short as possible.</p><h3>Advantages</h3><p>✅ Prevents race conditions</p><p>✅ Prevents lost updates</p><p>✅ Guarantees data consistency</p><p>✅ Great for financial applications</p><p>✅ Works well for inventory systems</p><h3>Disadvantages</h3><p>❌ Transactions may block each other</p><p>❌ Can reduce throughput</p><p>❌ Long-running transactions hurt performance</p><p>❌ Deadlocks become possible</p><h3>When Should You Use Pessimistic Locking?</h3><p>Use it when:</p><ul><li>Payment processing</li><li>Wallet balance</li><li>Inventory reservation</li><li>Ticket booking</li><li>Hotel reservation</li><li>Airline seats</li><li>Banking</li><li>Subscription renewals</li><li>Coupon redemption</li></ul><p>Avoid it for:</p><ul><li>Simple profile updates</li><li>Blog posts</li><li>User preferences</li></ul><h3>Interview Questions</h3><h3>Difference between lock, lock!, and with_lock</h3><p>lock</p><p>Used while querying.</p><pre>Account.lock.find(1)</pre><p>lock!</p><p>Locks an already loaded record.</p><pre>account.lock!</pre><p>with_lock</p><p>Starts a transaction, locks the record, executes the block, and commits automatically.</p><pre>account.with_lock do<br>  ...<br>end</pre><h3>What SQL does Rails generate?</h3><pre>SELECT *<br>FROM accounts<br>FOR UPDATE;</pre><h3>What happens if another transaction tries to update the same row?</h3><p>It waits until the first transaction commits or rolls back.</p><h3>When would you use SKIP LOCKED?</h3><p>When building:</p><ul><li>Job queues</li><li>Background workers</li><li>Task schedulers</li></ul><p>where workers should continue processing available rows instead of waiting.</p><h3>Key Takeaways</h3><ul><li>Pessimistic locking prevents concurrent modifications by locking rows before updates.</li><li>Rails supports it through lock, lock!, and with_lock.</li><li>PostgreSQL implements it using SELECT ... FOR UPDATE.</li><li>Keep transactions short to minimize lock contention.</li><li>Use features like NOWAIT and SKIP LOCKED when appropriate for advanced concurrency scenarios.</li><li>Pessimistic locking is ideal when data correctness is more important than maximizing concurrency.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6027a1ae19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolith vs Microservices: Architecture, Trade-offs, and How to Choose]]></title>
            <link>https://medium.com/@yashika270499/monolith-vs-microservices-architecture-trade-offs-and-how-to-choose-cba7902140b7?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cba7902140b7</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 09:11:17 GMT</pubDate>
            <atom:updated>2026-09-09T09:11:17.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When building a new application, one of the first architectural decisions a team faces is:</p><blockquote><strong><em>Should we build a monolith or use microservices?</em></strong></blockquote><p>The question sounds simple, but the answer isn’t.</p><p>Over the last decade, microservices have become one of the most discussed software architecture patterns. Many engineering teams moved from monolithic applications to microservices expecting better scalability, faster deployments, and greater flexibility.</p><p>But microservices also introduce significant complexity.</p><p>You now have multiple applications, multiple deployments, network communication, distributed failures, observability challenges, and often multiple databases.</p><p>A monolith, on the other hand, can be much simpler to develop, test, deploy, and operate.</p><p>So which one is better?</p><p>The answer is:</p><blockquote><strong><em>Neither is universally better. The right architecture depends on the application’s complexity, team structure, scalability requirements, and operational maturity.</em></strong></blockquote><p>In this article, we’ll explore:</p><ul><li>What a monolithic architecture is</li><li>What microservices are</li><li>How the two architectures differ</li><li>Advantages and disadvantages of each</li><li>Database architecture</li><li>Scaling</li><li>Deployment</li><li>Testing</li><li>Failure handling</li><li>Team organization</li><li>Modular monoliths</li><li>When to choose each architecture</li><li>How companies can migrate from a monolith to microservices</li><li>Common microservices mistakes</li><li>A practical decision framework</li></ul><h3>What Is Software Architecture?</h3><p>Before comparing monoliths and microservices, let’s understand what software architecture means.</p><p>Software architecture describes how the major components of an application are organized and how they interact with each other.</p><p>For example, an e-commerce application may contain:</p><pre>Users<br>Products<br>Orders<br>Payments<br>Inventory<br>Notifications</pre><p>The architectural question is:</p><blockquote><em>How should these components be organized and communicate with each other?</em></blockquote><p>A simple approach is to put everything into one application.</p><p>That’s a monolith.</p><p>Another approach is to split the application into multiple independently running services.</p><p>That’s microservices.</p><h3>What Is a Monolithic Architecture?</h3><p>A <strong>monolithic application</strong> is an application where most or all business functionality is developed, deployed, and operated as a single application.</p><p>For example:</p><pre>E-Commerce Application<br>                         |<br>        ---------------------------------------<br>        |          |          |       |       |<br>       Users    Products    Orders  Payments Inventory<br>        |          |          |       |       |<br>        ---------------------------------------<br>                         |<br>                      Database</pre><p>The application may have many modules internally, but it is deployed as one unit.</p><p>For example, a Rails application might contain:</p><pre>app/<br>├── models/<br>│   ├── user.rb<br>│   ├── product.rb<br>│   ├── order.rb<br>│   └── payment.rb<br>│<br>├── controllers/<br>│   ├── users_controller.rb<br>│   ├── products_controller.rb<br>│   ├── orders_controller.rb<br>│   └── payments_controller.rb<br>│<br>└── services/<br>    ├── payment_service.rb<br>    └── order_service.rb</pre><p>All of these components run inside the same application.</p><h3>How a Monolith Works</h3><p>Suppose a customer places an order.</p><p>The request might look like:</p><pre>Client<br>  |<br>  v<br>Rails Application<br>  |<br>  +--&gt; Validate User<br>  |<br>  +--&gt; Check Inventory<br>  |<br>  +--&gt; Create Order<br>  |<br>  +--&gt; Process Payment<br>  |<br>  +--&gt; Send Notification<br>  |<br>  v<br>Database</pre><p>Everything happens within the same application boundary.</p><p>The application can call another component directly:</p><pre>OrderService.call(user, product)</pre><p>There is no network request between these components.</p><p>This simplicity is one of the biggest advantages of a monolith.</p><h3>Advantages of a Monolith</h3><h3>1. Simple Development</h3><p>Developers work in one repository.</p><p>They don’t need to understand:</p><ul><li>service discovery</li><li>API gateways</li><li>distributed tracing</li><li>message brokers</li><li>inter-service authentication</li></ul><p>A developer can usually clone the repository and start working.</p><h3>2. Simple Deployment</h3><p>You deploy one application.</p><p>For example:</p><pre>git push<br>   |<br>   v<br>CI/CD<br>   |<br>   v<br>Deploy application</pre><p>With microservices, you may need to deploy multiple services independently.</p><h3>3. Simple Communication</h3><p>Inside a monolith:</p><pre>payment.process(order)</pre><p>With microservices:</p><pre>Order Service<br>      |<br>      | HTTP/gRPC/message<br>      v<br>Payment Service</pre><p>Network communication introduces latency and failure possibilities.</p><h3>4. Easier Transactions</h3><p>Suppose creating an order requires:</p><ol><li>Creating an order</li><li>Updating inventory</li><li>Creating a payment record</li></ol><p>In a monolith, these can potentially happen inside a single database transaction:</p><pre>ApplicationRecord.transaction do<br>  order.save!<br>  inventory.update!<br>  payment.save!<br>end</pre><p>If something fails:</p><pre>Order created<br>Inventory updated<br>Payment fails<br>       |<br>       v<br>Rollback</pre><p>The database can restore the previous state.</p><p>Distributed transactions across microservices are significantly more complicated.</p><h3>5. Easier Debugging</h3><p>If something fails:</p><pre>Request<br>  ↓<br>Application<br>  ↓<br>Database</pre><p>You can inspect one application’s logs and traces.</p><p>With microservices:</p><pre>API Gateway<br>   ↓<br>Order Service<br>   ↓<br>Inventory Service<br>   ↓<br>Payment Service<br>   ↓<br>Notification Service</pre><p>You may need to inspect logs from several services.</p><h3>Disadvantages of a Monolith</h3><p>Monoliths aren’t perfect.</p><p>As applications grow, problems can appear.</p><h3>1. Large Codebase</h3><p>A monolith can become difficult to understand.</p><p>Over time:</p><pre>app/<br>├── users<br>├── orders<br>├── payments<br>├── inventory<br>├── reporting<br>├── notifications<br>├── subscriptions<br>├── analytics<br>└── ...</pre><p>Everything exists in the same repository.</p><p>Without strong boundaries, modules can become tightly coupled.</p><h3>2. Scaling the Entire Application</h3><p>Suppose only the image-processing functionality needs more CPU.</p><p>With a traditional monolith:</p><pre>Application<br>     |<br>     +--- Users<br>     +--- Orders<br>     +--- Payments<br>     +--- Images</pre><p>You may have to scale the entire application.</p><p>You cannot independently scale only the image-processing component unless the architecture is designed for it.</p><h3>3. Deployment Coupling</h3><p>Suppose the payments team changes one small component.</p><p>If the entire application is deployed together, that change may go through the same deployment pipeline as everything else.</p><p>This can increase deployment risk.</p><h3>4. Large Teams Can Become Difficult to Manage</h3><p>Imagine 100 developers working in one repository.</p><p>You may encounter:</p><ul><li>merge conflicts</li><li>long CI pipelines</li><li>unclear ownership</li><li>tightly coupled modules</li><li>coordination overhead</li></ul><p>The problem isn’t necessarily that the application is a monolith.</p><p>The problem may be that the organization and architecture haven’t evolved together.</p><h3>What Is a Microservices Architecture?</h3><p>A microservices architecture divides an application into multiple independently deployable services.</p><p>Each service focuses on a specific business capability.</p><p>For example:</p><pre>API Gateway<br>                         |<br>       -------------------------------------<br>       |          |          |             |<br>       v          v          v             v<br>    User       Order      Payment      Inventory<br>   Service    Service     Service       Service<br>       |          |          |             |<br>       v          v          v             v<br>    Database   Database   Database      Database</pre><p>Each service can:</p><ul><li>have its own codebase</li><li>have its own deployment</li><li>have its own database</li><li>scale independently</li><li>be owned by a specific team</li></ul><h3>Example: E-Commerce Microservices</h3><p>Consider an e-commerce platform.</p><p>Instead of:</p><pre>E-Commerce Monolith</pre><p>we might have:</p><pre>User Service<br>Order Service<br>Product Service<br>Inventory Service<br>Payment Service<br>Notification Service</pre><p>Each service owns a specific responsibility.</p><p>For example:</p><h3>User Service</h3><p>Responsible for:</p><ul><li>registration</li><li>login</li><li>profiles</li><li>authentication</li></ul><h3>Product Service</h3><p>Responsible for:</p><ul><li>products</li><li>categories</li><li>pricing</li></ul><h3>Order Service</h3><p>Responsible for:</p><ul><li>orders</li><li>order lifecycle</li><li>order history</li></ul><h3>Payment Service</h3><p>Responsible for:</p><ul><li>payment processing</li><li>refunds</li><li>payment status</li></ul><h3>Notification Service</h3><p>Responsible for:</p><ul><li>emails</li><li>SMS</li><li>push notifications</li></ul><h3>The Most Important Microservices Principle</h3><p>The goal is not:</p><blockquote><em>“Split the application into many small applications.”</em></blockquote><p>The goal is:</p><blockquote><strong><em>Create independently deployable services around meaningful business boundaries.</em></strong></blockquote><p>This distinction is important.</p><p>A system with 50 tiny services isn’t automatically better than a system with 5 well-designed services.</p><h3>Advantages of Microservices</h3><h3>1. Independent Deployment</h3><p>A payment service can be deployed without deploying the order service.</p><pre>Payment Service<br>      |<br>      v<br>Deploy independently</pre><p>This can enable teams to release features faster.</p><h3>2. Independent Scaling</h3><p>Suppose the order service receives significantly more traffic than the user service.</p><p>You can scale them independently:</p><pre>User Service<br>Instances: 3</pre><pre>Order Service<br>Instances: 20</pre><pre>Payment Service<br>Instances: 5</pre><h3>3. Team Ownership</h3><p>Different teams can own different services.</p><pre>Team A → User Service<br>Team B → Order Service<br>Team C → Payment Service<br>Team D → Notification Service</pre><p>This can reduce coordination between teams.</p><h3>4. Technology Flexibility</h3><p>Different services can potentially use different technologies.</p><p>For example:</p><pre>User Service      → Rails<br>Payment Service   → Java<br>Recommendation   → Python<br>Notification     → Go</pre><p>However, just because you can use multiple languages doesn’t mean you should.</p><p>Technology diversity introduces its own operational costs.</p><h3>5. Fault Isolation</h3><p>Suppose the recommendation service fails.</p><p>Ideally:</p><pre>Recommendation Service ❌</pre><pre>Order Service           ✅<br>Payment Service         ✅<br>User Service            ✅</pre><p>The entire application doesn’t necessarily have to go down.</p><p>But this only works if services are designed with failure isolation in mind.</p><h3>Disadvantages of Microservices</h3><p>This is where many teams underestimate the cost.</p><h3>1. Network Communication</h3><p>Inside a monolith:</p><pre>payment.process(order)</pre><p>With microservices:</p><pre>Order Service<br>      |<br>      | HTTP<br>      v<br>Payment Service</pre><p>The network can fail.</p><p>Possible problems include:</p><ul><li>timeout</li><li>connection failure</li><li>DNS failure</li><li>retry storms</li><li>latency</li><li>duplicate requests</li></ul><p>Communication becomes a major architectural concern.</p><p>We’ll explore this in detail in the next article.</p><h3>2. Distributed Transactions</h3><p>Consider:</p><pre>Order Service<br>     |<br>     +--&gt; Inventory Service<br>     |<br>     +--&gt; Payment Service</pre><p>What happens if:</p><pre>Order created       ✅<br>Inventory updated   ✅<br>Payment failed      ❌</pre><p>You can’t simply rollback all services using a normal database transaction.</p><p>This is one of the biggest differences between monolithic and distributed systems.</p><p>Solutions may involve:</p><ul><li>Saga pattern</li><li>compensating transactions</li><li>event-driven architecture</li><li>idempotency</li></ul><h3>3. Debugging Becomes Harder</h3><p>A single user request might travel through:</p><pre>API Gateway<br>    ↓<br>Order Service<br>    ↓<br>Inventory Service<br>    ↓<br>Payment Service<br>    ↓<br>Notification Service</pre><p>If the request fails, which service caused the problem?</p><p>You need tools such as:</p><ul><li>centralized logging</li><li>distributed tracing</li><li>correlation IDs</li><li>metrics</li><li>monitoring</li></ul><h3>4. Operational Complexity</h3><p>A monolith might require:</p><pre>Application<br>Database<br>Redis</pre><p>A microservices system might require:</p><pre>10 Services<br>10 Databases<br>Message Broker<br>API Gateway<br>Service Discovery<br>Centralized Logging<br>Distributed Tracing<br>Monitoring<br>Secrets Management<br>CI/CD pipelines</pre><p>The operational burden increases significantly.</p><h3>5. Data Consistency</h3><p>In a monolith, multiple modules can share a database.</p><p>With microservices, each service ideally owns its data.</p><pre>Order Service<br>     |<br> Orders DB</pre><pre>Payment Service<br>     |<br> Payments DB</pre><p>Now querying data across services becomes more complicated.</p><p>You can’t simply write:</p><pre>SELECT *<br>FROM orders<br>JOIN payments<br>ON payments.order_id = orders.id;</pre><p>because the tables may exist in completely different databases.</p><h3>Shared Database vs Database per Service</h3><p>This is one of the most important architectural decisions.</p><h3>Shared Database</h3><pre>Order Service --------\<br>Payment Service ------- &gt; PostgreSQL<br>Inventory Service ----/</pre><p>It’s easier initially.</p><p>But services become coupled through the database.</p><p>One service might directly modify another service’s tables.</p><p>This weakens service boundaries.</p><h3>Database per Service</h3><pre>Order Service<br>     |<br> Orders DB</pre><pre>Payment Service<br>     |<br> Payments DB</pre><pre>Inventory Service<br>     |<br> Inventory DB</pre><p>This provides stronger ownership.</p><p>But now cross-service queries and transactions become harder.</p><h3>Monolith vs Microservices: Database Comparison</h3><p>Area</p><p>Monolith</p><p>Microservices</p><p>Database</p><p>Usually shared</p><p>Usually owned by service</p><p>Transactions</p><p>Easier</p><p>More complex</p><p>Joins</p><p>Easy</p><p>Usually avoided across services</p><p>Consistency</p><p>Easier</p><p>Often eventual</p><p>Data ownership</p><p>Shared</p><p>Explicit</p><p>Reporting</p><p>Easier</p><p>Requires aggregation</p><h3>Scaling Comparison</h3><p>Suppose your application receives:</p><pre>10,000 requests/second</pre><p>A monolith can still scale.</p><p>For example:</p><pre>Load Balancer<br>      |<br> -----------------<br> |       |       |<br>App     App     App</pre><p>There is nothing inherently wrong with scaling a monolith horizontally.</p><p>Microservices simply allow more granular scaling.</p><pre>Order Service → 20 instances<br>User Service → 5 instances<br>Payment Service → 10 instances</pre><p>Therefore:</p><blockquote><strong><em>High traffic does not automatically mean you need microservices.</em></strong></blockquote><p>A well-designed monolith can handle significant scale.</p><h3>Deployment Comparison</h3><h3>Monolith</h3><pre>Code<br> ↓<br>Build<br> ↓<br>Test<br> ↓<br>Deploy<br> ↓<br>Application</pre><p>Usually one deployment pipeline.</p><h3>Microservices</h3><pre>Order Service<br>     ↓<br>Pipeline<br>     ↓<br>Deploy</pre><pre>Payment Service<br>     ↓<br>Pipeline<br>     ↓<br>Deploy</pre><pre>Inventory Service<br>     ↓<br>Pipeline<br>     ↓<br>Deploy</pre><p>You gain independent deployments but also need to manage multiple pipelines.</p><h3>Testing Comparison</h3><h3>Monolith</h3><p>You can run:</p><pre>Unit Tests<br>Integration Tests<br>System Tests</pre><p>Testing is relatively straightforward because components are inside one application.</p><h3>Microservices</h3><p>You need additional testing strategies:</p><pre>Unit Tests<br>     ↓<br>Service Tests<br>     ↓<br>Contract Tests<br>     ↓<br>Integration Tests<br>     ↓<br>End-to-End Tests</pre><p>You need to verify not only that each service works but also that services understand each other’s contracts.</p><h3>Failure Handling</h3><p>Failure is much more visible in distributed systems.</p><p>Suppose:</p><pre>Order Service<br>     |<br>     v<br>Payment Service</pre><p>Payment service takes 10 seconds to respond.</p><p>Should the order request wait?</p><p>Probably not indefinitely.</p><p>You may need:</p><ul><li>timeouts</li><li>retries</li><li>circuit breakers</li><li>fallback behavior</li><li>asynchronous processing</li></ul><p>For example:</p><pre>Order Created<br>     |<br>     v<br>Publish Event<br>     |<br>     v<br>Payment Processing<br>     |<br>     v<br>Payment Completed</pre><p>This allows parts of the system to operate asynchronously.</p><h3>Monolith vs Modular Monolith vs Microservices</h3><p>There is an important architecture between the two extremes:</p><blockquote><strong><em>Modular Monolith</em></strong></blockquote><p>A modular monolith is still deployed as one application, but its internal components have strict boundaries.</p><p>For example:</p><pre>Rails Application<br>                     |<br>       -----------------------------<br>       |            |              |<br>     Orders       Payments      Inventory<br>       |            |              |<br>       -----------------------------<br>                     |<br>                 Database</pre><p>The application is deployed as one unit, but modules are isolated.</p><p>This can provide many benefits of good architecture without immediately introducing distributed-system complexity.</p><h3>Why Modular Monoliths Are Important</h3><p>A common mistake is:</p><pre>Monolith<br>   ↓<br>&quot;We need microservices&quot;<br>   ↓<br>20 services</pre><p>A better approach may be:</p><pre>Monolith<br>   ↓<br>Identify boundaries<br>   ↓<br>Create modules<br>   ↓<br>Reduce coupling<br>   ↓<br>Measure actual bottlenecks<br>   ↓<br>Extract services only when necessary</pre><p>This gives the team time to understand the domain before introducing network boundaries.</p><h3>When Should You Choose a Monolith?</h3><p>A monolith is often a good choice when:</p><ul><li>You’re building a new product</li><li>The team is small</li><li>The domain is still changing</li><li>Requirements are uncertain</li><li>You want fast iteration</li><li>Operational resources are limited</li><li>You don’t have strong service boundaries yet</li></ul><p>For many startups, this is an excellent starting point.</p><h3>When Should You Consider Microservices?</h3><p>Microservices may make sense when:</p><h3>1. Teams Need Independent Ownership</h3><p>If multiple teams need to work independently on different business domains, service boundaries can help.</p><h3>2. Components Scale Differently</h3><p>For example:</p><pre>Image Processing → Very high CPU<br>User Management → Low traffic</pre><p>Independent scaling could be valuable.</p><h3>3. Independent Deployments Are Important</h3><p>If one team’s release shouldn’t require coordinating with five other teams, independently deployable services can help.</p><h3>4. Strong Domain Boundaries Exist</h3><p>For example:</p><pre>Payments<br>Identity<br>Orders<br>Shipping</pre><p>If these are clearly separated business domains, they may be good candidates for service boundaries.</p><h3>When Microservices Are a Bad Idea</h3><p>Don’t choose microservices simply because:</p><blockquote><em>“Netflix uses them.”</em></blockquote><p>Or:</p><blockquote><em>“Our application is getting bigger.”</em></blockquote><p>Or:</p><blockquote><em>“Microservices are more scalable.”</em></blockquote><p>Microservices may be a bad choice when:</p><ul><li>The team is small</li><li>The domain is poorly understood</li><li>You don’t have DevOps maturity</li><li>Monitoring is weak</li><li>Deployment automation is poor</li><li>Services need constant communication</li><li>Data boundaries aren’t clear</li></ul><p>If every service constantly calls every other service:</p><pre>A → B<br>A → C<br>A → D</pre><pre>B → A<br>B → C<br>B → D</pre><pre>C → A<br>C → B<br>C → D</pre><p>you haven’t created independent services.</p><p>You’ve created a <strong>distributed monolith</strong>.</p><h3>What Is a Distributed Monolith?</h3><p>A distributed monolith has multiple services but behaves like one tightly coupled application.</p><p>For example:</p><pre>Order<br>  ↓<br>Inventory<br>  ↓<br>Payment<br>  ↓<br>User<br>  ↓<br>Notification</pre><p>Every request requires several services to be available.</p><p>Deploying one service requires another service to be updated.</p><p>At this point, you’ve taken the complexity of a monolith and added network complexity on top of it.</p><p>That’s one of the worst outcomes.</p><h3>The Importance of Service Boundaries</h3><p>Good microservices have clear responsibilities.</p><p>For example:</p><pre>Payment Service</pre><pre>Owns:<br>- Payments<br>- Refunds<br>- Payment status</pre><pre>Doesn&#39;t own:<br>- Orders<br>- Inventory<br>- User profiles</pre><p>A service should ideally own its business logic and data.</p><p>This concept is often described as:</p><blockquote><strong><em>Bounded Context</em></strong></blockquote><p>from Domain-Driven Design.</p><h3>Don’t Start With the Most Complex Service</h3><p>When extracting your first service, choose a capability with:</p><ul><li>Clear ownership</li><li>Clear boundaries</li><li>Limited dependencies</li><li>Independent scaling requirements</li><li>Minimal cross-service transactions</li></ul><p>Don’t start by extracting the most interconnected component.</p><h3>A Practical Decision Framework</h3><p>Before choosing microservices, ask:</p><h3>Question 1</h3><p>Do we actually have a scaling problem?</p><p>If not, don’t introduce distributed complexity just for future scale.</p><h3>Question 2</h3><p>Do different parts of the application need independent deployments?</p><p>If yes, microservices may help.</p><h3>Question 3</h3><p>Do we have clear domain boundaries?</p><p>If no, start with a modular monolith.</p><h3>Question 4</h3><p>Can our team operate distributed systems?</p><p>Do we have:</p><ul><li>monitoring</li><li>logging</li><li>tracing</li><li>CI/CD</li><li>infrastructure automation</li><li>incident response</li></ul><p>If not, microservices may be premature.</p><h3>Question 5</h3><p>Can services operate independently?</p><p>If every service requires five other services for every request, reconsider the architecture.</p><h3>A Simple Comparison</h3><p>Feature</p><p>Monolith</p><p>Modular Monolith</p><p>Microservices</p><p>Deployment</p><p>Single</p><p>Single</p><p>Independent</p><p>Codebase</p><p>Usually one</p><p>One</p><p>Multiple</p><p>Database</p><p>Usually shared</p><p>Usually shared</p><p>Usually separate</p><p>Scaling</p><p>Application-level</p><p>Application-level</p><p>Service-level</p><p>Communication</p><p>In-process</p><p>In-process</p><p>Network</p><p>Transactions</p><p>Easy</p><p>Easy</p><p>Complex</p><p>Debugging</p><p>Easier</p><p>Easier</p><p>Harder</p><p>Operations</p><p>Simpler</p><p>Simpler</p><p>Complex</p><p>Team independence</p><p>Lower</p><p>Medium</p><p>Higher</p><p>Infrastructure cost</p><p>Lower</p><p>Lower</p><p>Higher</p><p>Failure isolation</p><p>Lower</p><p>Medium</p><p>Higher</p><p>Initial development speed</p><p>High</p><p>High</p><p>Lower</p><p>Long-term complexity</p><p>Can increase</p><p>Controlled</p><p>High</p><h3>A Common Misconception</h3><h3>“Microservices automatically scale better.”</h3><p>Not necessarily.</p><p>A monolith can scale horizontally:</p><pre>Load Balancer<br>             /      |      \<br>            /       |       \<br>         App       App      App</pre><p>Microservices simply provide more granular scaling:</p><pre>Order Service → 20 instances<br>User Service → 3 instances<br>Payment Service → 8 instances</pre><p>The benefit is flexibility, not magic scalability.</p><h3>What Would I Choose?</h3><p>For a new application with a small or medium-sized team, I’d generally start with:</p><blockquote><strong><em>A well-structured modular monolith.</em></strong></blockquote><p>Build clear boundaries.</p><p>Measure the system.</p><p>Understand where the real problems are.</p><p>Then extract services when there is a concrete reason.</p><p>For an organization with:</p><ul><li>many teams</li><li>clear business domains</li><li>independent deployment requirements</li><li>different scaling requirements</li><li>mature DevOps practices</li></ul><p>microservices can be a very effective architecture.</p><h3>Conclusion</h3><p>Monoliths and microservices aren’t competing technologies.</p><p>They are architectural choices with different trade-offs.</p><p>A monolith provides:</p><ul><li>simplicity</li><li>easy transactions</li><li>straightforward deployment</li><li>simpler debugging</li></ul><p>Microservices provide:</p><ul><li>independent deployment</li><li>independent scaling</li><li>team autonomy</li><li>stronger service boundaries</li><li>potential fault isolation</li></ul><p>But microservices also introduce:</p><ul><li>network failures</li><li>distributed transactions</li><li>data consistency challenges</li><li>observability requirements</li><li>operational complexity</li></ul><p>The best architecture isn’t the one that sounds the most modern.</p><p>It’s the one that solves your actual problems without introducing unnecessary complexity.</p><blockquote><strong><em>Don’t choose microservices because your application is becoming successful. Choose them when the benefits of independence outweigh the complexity of distribution.</em></strong></blockquote><p>And if you’re starting with a monolith, that doesn’t mean you’ve made a permanent decision. A well-designed modular monolith can be an excellent foundation for gradually extracting services when the need becomes real.</p><h3>What’s Next?</h3><p>Choosing microservices is only the beginning.</p><p>Once an application is split into multiple services, a much bigger question appears:</p><blockquote><strong><em>How do these services communicate with each other?</em></strong></blockquote><p>Should they use:</p><ul><li>REST APIs?</li><li>gRPC?</li><li>Message queues?</li><li>Kafka?</li><li>RabbitMQ?</li><li>Amazon SQS?</li><li>Events?</li></ul><p>Each approach has different trade-offs around latency, reliability, scalability, consistency, and failure handling.</p><p>That’s what we’ll explore in the next article:</p><p><strong>Microservices Communication: REST vs gRPC vs Message Queues vs Event-Driven Architecture.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cba7902140b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Ponytail? A Beginner’s Guide to the AI Coding Companion Everyone Is Talking About]]></title>
            <link>https://medium.com/@yashika270499/what-is-ponytail-a-beginners-guide-to-the-ai-coding-companion-everyone-is-talking-about-89ff76682b5d?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ff76682b5d</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 09:03:13 GMT</pubDate>
            <atom:updated>2026-08-04T09:03:13.910Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>⚠️ Note:</em></strong><em> AI developer tools evolve incredibly fast. Installation steps, supported editors, AI models, and configuration options may change over time. This article is </em><strong><em>not intended to be official documentation</em></strong><em>. Instead, its goal is to help you understand </em><strong><em>what Ponytail is, why it exists, and when you might want to use it</em></strong><em>. Before installing or configuring Ponytail, always refer to its official documentation for the latest instructions.</em></blockquote><h3>Introduction</h3><p>If you’ve recently spent time on X (Twitter), Reddit, or developer communities, you’ve probably seen people talking about <strong>Ponytail</strong>.</p><p>Some developers call it an AI coding assistant.</p><p>Others think it’s an alternative to Cursor.</p><p>Some believe it’s a replacement for Claude Code.</p><p>And many assume it’s another Large Language Model (LLM) like ChatGPT or Claude.</p><p>None of these descriptions are entirely accurate.</p><p>This confusion exists because Ponytail is different from most AI tools developers are familiar with.</p><p>In this article, we’ll break down exactly what Ponytail is, what it is not, how it fits into the AI coding ecosystem, and when it makes sense to use it.</p><h3>The Biggest Misconception About Ponytail</h3><p>The first thing to understand is this:</p><p><strong>Ponytail is not an AI model.</strong></p><p>It cannot answer questions by itself.</p><p>It cannot generate code by itself.</p><p>It cannot replace ChatGPT, Claude, Gemini, or any other language model.</p><p>Instead, Ponytail works <strong>alongside</strong> an AI coding agent.</p><p>Think of it as a layer that influences how the AI approaches programming tasks.</p><h3>Understanding the AI Coding Ecosystem</h3><p>Many developers mix together editors, AI models, and coding agents.</p><p>These are different pieces of the puzzle.</p><p>Imagine you’re building a Rails application.</p><p>You have:</p><pre>VS Code<br>    ↓<br>AI Coding Agent<br>    ↓<br>LLM (Claude / GPT / Gemini)</pre><p>Each layer has a different responsibility.</p><h3>VS Code</h3><p>VS Code is simply your editor.</p><p>It doesn’t understand your code or generate anything on its own.</p><h3>AI Model</h3><p>Claude</p><p>GPT</p><p>Gemini</p><p>These are language models.</p><p>They understand natural language and generate code.</p><p>However, by themselves they don’t know how to edit files inside your project or interact with your development environment.</p><h3>AI Coding Agent</h3><p>An AI coding agent connects your editor to an AI model.</p><p>It can:</p><ul><li>Read project files</li><li>Edit code</li><li>Create new files</li><li>Run commands</li><li>Analyze your repository</li><li>Suggest refactoring</li><li>Generate tests</li></ul><p>Examples include various AI-powered coding assistants and editor integrations.</p><h3>Ponytail</h3><p>Ponytail sits on top of this workflow.</p><p>Instead of replacing your AI, it attempts to improve <strong>how the AI behaves while writing code</strong>.</p><h3>An Analogy</h3><p>Imagine you’re hiring a software engineer.</p><p>Without guidance, they might:</p><ul><li>create unnecessary abstractions</li><li>introduce extra classes</li><li>over-engineer a simple solution</li><li>use complex design patterns for small problems</li></ul><p>Now imagine giving that engineer a document that says:</p><ul><li>Keep things simple.</li><li>Don’t create classes unless necessary.</li><li>Prefer existing libraries.</li><li>Avoid unnecessary complexity.</li><li>Write code another developer can understand quickly.</li></ul><p>The engineer hasn’t changed.</p><p>Their instructions have.</p><p>Ponytail plays a similar role for AI coding assistants.</p><h3>What Problem Does Ponytail Solve?</h3><p>As AI became better at writing code, developers noticed recurring issues.</p><p>The AI often:</p><ul><li>creates more files than necessary</li><li>writes excessive boilerplate</li><li>introduces unnecessary abstractions</li><li>overuses design patterns</li><li>invents helper classes</li><li>makes small tasks more complicated than they need to be</li></ul><p>Sometimes this is useful.</p><p>Often it isn’t.</p><p>Ponytail aims to steer the AI toward simpler, more maintainable solutions.</p><h3>What Ponytail Is NOT</h3><p>Ponytail is <strong>not</strong>:</p><ul><li>another version of ChatGPT</li><li>another LLM</li><li>a replacement for Claude</li><li>a replacement for Cursor</li><li>an IDE</li><li>a code editor</li><li>a compiler</li></ul><p>Understanding this distinction removes most of the confusion.</p><h3>Can Ponytail Work Without an AI?</h3><p>No.</p><p>If you only install Ponytail, nothing happens.</p><p>You still need an AI coding agent backed by an AI model.</p><p>Think of it like this:</p><pre>VS Code<br>❌</pre><pre>VS Code + Ponytail<br>❌</pre><pre>VS Code + AI Agent<br>✅</pre><pre>VS Code + AI Agent + Ponytail<br>✅</pre><h3>Does Ponytail Replace Cursor?</h3><p>No.</p><p>Cursor is a complete AI-powered editor.</p><p>Ponytail is not.</p><p>Cursor provides:</p><ul><li>editor integration</li><li>AI chat</li><li>autocomplete</li><li>repository understanding</li></ul><p>Ponytail focuses on influencing how an AI coding assistant approaches problems rather than replacing the editor itself.</p><h3>Does Ponytail Replace Claude?</h3><p>No.</p><p>Claude is the intelligence.</p><p>Ponytail provides guidance.</p><p>Without Claude (or another supported model), Ponytail has nothing to reason with.</p><h3>Does Ponytail Reduce Token Usage?</h3><p>This is one of the most common questions.</p><p>The answer is:</p><p><strong>Not directly.</strong></p><p>Ponytail does not magically reduce the number of tokens consumed.</p><p>However, by encouraging the AI to produce smaller, simpler solutions with fewer unnecessary edits, some workflows may naturally involve fewer generated tokens.</p><p>This depends on:</p><ul><li>the AI model</li><li>the coding task</li><li>the prompts</li><li>the agent’s behavior</li></ul><p>So any reduction is a side effect of simpler outputs, not a guaranteed feature.</p><h3>Is Ponytail Free?</h3><p>Ponytail itself has generally been made available as an open-source project.</p><p>However, remember:</p><p>Using Ponytail does <strong>not</strong> eliminate the need for an AI model.</p><p>If your coding assistant relies on a paid AI service or API, those costs still apply.</p><p>Think of Ponytail as improving the workflow rather than replacing the underlying AI.</p><h3>When Should You Use Ponytail?</h3><p>Ponytail can be valuable when:</p><ul><li>working on large production codebases</li><li>contributing to open-source projects</li><li>maintaining mature Rails applications</li><li>reviewing AI-generated code</li><li>encouraging simpler implementations</li><li>reducing unnecessary abstractions</li></ul><p>These are situations where readability and maintainability often matter more than generating the maximum amount of code.</p><h3>When Should You Avoid It?</h3><p>Ponytail may not add much value if you’re:</p><ul><li>learning programming from scratch</li><li>writing small throwaway scripts</li><li>experimenting with new ideas</li><li>using AI only for quick code snippets</li></ul><p>In these cases, a standard AI assistant may already be sufficient.</p><h3>A Rails Example</h3><p>Suppose you ask your AI:</p><blockquote><em>“Optimize this ActiveRecord query.”</em></blockquote><p>Without guidance, the AI might introduce several service objects, helper modules, and layers of abstraction.</p><p>With a “keep it simple” philosophy, the AI is more likely to suggest:</p><ul><li>adding the correct index</li><li>using includes</li><li>avoiding N+1 queries</li><li>simplifying the ActiveRecord chain</li><li>making a small, focused improvement</li></ul><p>This often aligns well with how experienced Rails developers prefer to evolve applications.</p><h3>Frequently Asked Questions</h3><h3>Is Ponytail another AI?</h3><p>No.</p><h3>Can Ponytail write code?</h3><p>Not by itself.</p><h3>Does Ponytail work without Claude or another AI model?</h3><p>No.</p><h3>Does Ponytail replace Cursor?</h3><p>No.</p><h3>Does Ponytail replace VS Code?</h3><p>No.</p><h3>Is Ponytail a code editor?</h3><p>No.</p><h3>Does Ponytail guarantee better code?</h3><p>No. It provides guidance, but you should always review AI-generated code before merging it into production.</p><h3>Final Thoughts</h3><p>AI-assisted development is evolving at an incredible pace. New models, editors, and coding agents appear regularly, and the surrounding ecosystem changes just as quickly.</p><p>Ponytail is best thought of as <strong>a way to influence how an AI coding assistant approaches software development</strong>, encouraging simpler, more maintainable solutions rather than acting as a new AI model or editor.</p><p>Whether Ponytail becomes part of your daily workflow depends on your projects, your preferred tools, and how much you value AI-generated code that favors clarity over complexity.</p><p>As with any AI tool, the most important skill isn’t learning a specific product — it’s understanding where that product fits into the broader development workflow.</p><p>If this article introduced you to Ponytail for the first time, take a few minutes to explore its latest documentation, experiment with it in a small project, and decide whether its philosophy aligns with the way you like to build software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ff76682b5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimistic Locking in Ruby on Rails: Prevent Lost Updates with lock_version]]></title>
            <link>https://medium.com/@yashika270499/optimistic-locking-in-ruby-on-rails-prevent-lost-updates-with-lock-version-8c5a44bd7f8a?source=rss-b5b68cc155e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c5a44bd7f8a</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[locking]]></category>
            <dc:creator><![CDATA[Yashika Vijayvargiya]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 12:04:10 GMT</pubDate>
            <atom:updated>2026-07-29T10:46:05.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RP7kRC5g727RKLpS" /></figure><p>Senior Ruby on Rails Engineer sharing practical insights on Rails, React, system design, performance optimization,. My goal is to simplify complex concepts through real-world examples and hands-on experiences.</p><p><em>Originally published at </em><a href="https://railswithyashika.hashnode.dev/part-3-optimistic-locking-in-rails-preventing-lost-updates-without-blocking-users"><em>https://railswithyashika.hashnode.dev</em></a><em> on July 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c5a44bd7f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>