<?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"><channel><title><![CDATA[Rimaz Saththar]]></title><description><![CDATA[Notes on backend engineering, distributed systems and open source.]]></description><link>https://rimazsaththar.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 23:03:59 GMT</lastBuildDate><atom:link href="https://rimazsaththar.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Two Users Bought the Last Item. Your Database Allowed It.]]></title><description><![CDATA[50 buyers, 1 item: Postgres and MySQL both oversold it. Why REPEATABLE READ differs between them, and four fixes benchmarked in Go.]]></description><link>https://rimazsaththar.hashnode.dev/two-users-bought-the-last-item-database-race-condition</link><guid isPermaLink="true">https://rimazsaththar.hashnode.dev/two-users-bought-the-last-item-database-race-condition</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Rimaz Saththar]]></dc:creator><pubDate>Mon, 30 Nov 2026 11:57:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/72bf06d9-3e37-4014-9e73-1c7a34aa890f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>TL;DR</h2>
<ul>
<li>The usual "read the stock, check it, write it back" code oversold a single item on both Postgres and MySQL. With 50 buyers arriving at the same moment, one item got an average of <strong>47.5 orders on Postgres and 48.1 on MySQL</strong>.</li>
<li>Switching to <code>REPEATABLE READ</code> stopped it on Postgres (49 buyers got an error instead). On MySQL it changed nothing, because <code>REPEATABLE READ</code> is already MySQL's default and it was the level that just sold one item 48 times.</li>
<li>The fix that was correct and also the fastest on both databases: one conditional <code>UPDATE ... WHERE stock &gt; 0</code>, then check how many rows it changed.</li>
</ul>
<hr />
<p>Here's a bug report every shop eventually gets: "We had one left. Two people bought it."</p>
<p>The first time I thought about this properly, my instinct was that it had to be rare. Two customers would need to click Buy within a few milliseconds of each other, on the same item, when there's exactly one left. Surely the database handles that?</p>
<p>So I tested it. I wrote the checkout code most of us write, pointed 50 buyers at a product with a stock of 1, and released them all at once. On Postgres the item sold an average of 47.5 times. On MySQL, 48.1 times. In the worst rounds, all 50 buyers got an order for a single item.</p>
<p>This post walks through why that happens, why the isolation level you'd reach for first doesn't behave the same on Postgres and MySQL, and which of the four common fixes actually held up when I measured them.</p>
<h2>The code most of us write</h2>
<p>Here's a checkout written the way I've seen it in a lot of codebases (error handling trimmed so it fits):</p>
<pre><code class="language-go">tx, _ := db.BeginTx(ctx, nil)
defer tx.Rollback()

var stock int
tx.QueryRowContext(ctx, "SELECT stock FROM products WHERE id = $1", id).Scan(&amp;stock)

if stock &lt;= 0 {
    return ErrSoldOut
}

tx.ExecContext(ctx, "UPDATE products SET stock = $1 WHERE id = $2", stock-1, id)
tx.ExecContext(ctx, "INSERT INTO orders (product_id) VALUES ($1)", id)
return tx.Commit()
</code></pre>
<p>It's in a transaction. It checks the stock before selling. If you use an ORM, it's probably the same thing in a friendlier shape: load the product, <code>product.Stock--</code>, save it.</p>
<p>It reads like it can't oversell. It will pass every test you write for it, because tests usually run one request at a time. The problem only shows up when requests overlap, and on a busy product launch they overlap a lot.</p>
<h2>The experiment</h2>
<p>I wanted real numbers instead of a theory, so I set up:</p>
<ul>
<li><strong>Postgres 18</strong> and <strong>MySQL 8.4</strong>, both in Docker with default settings</li>
<li>A <code>products</code> table with one row and an <code>orders</code> table</li>
<li>50 goroutines, each acting as one buyer, all waiting on a channel that I close as a starting gun so they hit the database together</li>
<li>20 rounds per approach, with the stock reset to 1 before each round</li>
</ul>
<p>Releasing everyone at once is deliberate. It's what a ticket release, a limited drop or a flash sale looks like: lots of people pressing Buy in the same second.</p>
<p>Here's what the code above did:</p>
<table>
<thead>
<tr>
<th>Database (default isolation)</th>
<th>Rounds oversold</th>
<th>Avg orders for 1 item</th>
<th>Worst round</th>
</tr>
</thead>
<tbody><tr>
<td>Postgres (<code>READ COMMITTED</code>)</td>
<td>19 of 20</td>
<td>47.5</td>
<td>50</td>
</tr>
<tr>
<td>MySQL (<code>REPEATABLE READ</code>)</td>
<td>20 of 20</td>
<td>48.1</td>
<td>50</td>
</tr>
</tbody></table>
<p>Then I tried a bigger sale: 1,000 items in stock and 3,000 purchase attempts from 50 buyers. Both databases accepted all 3,000 orders. And the part that made me laugh: when it finished, the stock column on Postgres still said <strong>933 items left</strong>. The shop had sold three times its stock and believed it had barely started.</p>
<h2>Why it happens</h2>
<p>The transaction protects less than it looks like it does. Here are two buyers on Postgres's default level, <code>READ COMMITTED</code>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/a3bfa8f1-5dba-4783-b61b-1cf37dddc984.png" alt="Timeline of two buyers who both read a stock of 1 before either writes, so both write 0 and two orders are created for one item" style="display:block;margin:0 auto" />

<ol>
<li>Buyer A reads the stock: 1.</li>
<li>Buyer B reads the stock: also 1, because A hasn't committed anything yet.</li>
<li>Both pass the <code>stock &lt;= 0</code> check.</li>
<li>A writes <code>stock = 0</code> and creates an order.</li>
<li>B's <code>UPDATE</code> waits for A's row lock. When A commits, B carries on and writes <code>stock = 0</code> too, then creates a second order.</li>
</ol>
<p>Nothing failed. Every statement did exactly what it was told. The problem is that B made its decision using a value that was already out of date, and the database had no way of knowing the <code>0</code> it was writing came from that stale read.</p>
<p>This is called a <strong>lost update</strong>: two transactions read the same value, both write a new one based on it, and one write silently replaces the other. It also explains the 933. With 50 buyers overlapping, a whole group would read the same stock, each write "that number minus one", and the counter would only go down by one for the entire group.</p>
<p>One more thing worth noticing: a <code>CHECK (stock &gt;= 0)</code> constraint wouldn't have caught any of this. The code never wrote a negative number. It wrote <code>0</code>, 49 times.</p>
<h2>"Just use a stricter isolation level"</h2>
<p>This was my first idea, and it's where Postgres and MySQL split.</p>
<p><code>REPEATABLE READ</code> sounds like exactly what we need: the transaction works from a consistent snapshot, so surely it notices when someone else changes the row? I ran the same code with that isolation level set explicitly:</p>
<table>
<thead>
<tr>
<th>Database at <code>REPEATABLE READ</code></th>
<th>Rounds oversold</th>
<th>Avg orders for 1 item</th>
<th>Errors</th>
</tr>
</thead>
<tbody><tr>
<td>Postgres</td>
<td>0 of 20</td>
<td>1.0</td>
<td>980 (49 per round)</td>
</tr>
<tr>
<td>MySQL</td>
<td>20 of 20</td>
<td>50.0</td>
<td>0</td>
</tr>
</tbody></table>
<p>Same code, same isolation level name, opposite results.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/0db5d985-d574-4552-831b-221513db5027.png" alt="At REPEATABLE READ, Postgres rejects the second buyer's update with a serialization error, while MySQL lets it write and creates a second order" style="display:block;margin:0 auto" />

<p><strong>Postgres</strong> refuses to let a <code>REPEATABLE READ</code> transaction update a row that another transaction changed after its snapshot was taken. When buyer B's <code>UPDATE</code> gets the lock and finds that A already changed the row, it fails with:</p>
<pre><code class="language-plaintext">ERROR: could not serialize access due to concurrent update
</code></pre>
<p>So one buyer wins and the other 49 get an error. No overselling.</p>
<p><strong>MySQL (InnoDB)</strong> handles it differently. Under <code>REPEATABLE READ</code>, a plain <code>SELECT</code> reads from your snapshot and takes no locks. But an <code>UPDATE</code> always works on the latest committed version of the row, and InnoDB doesn't check whether that row changed since your snapshot. So B's <code>UPDATE</code> waits for A, then happily writes the <code>0</code> it calculated from the old value. MySQL's documentation does say the snapshot applies to <code>SELECT</code> statements and not necessarily to writes, but it's easy to go years without reading that line.</p>
<p>That's why I said in the TL;DR that MySQL's default didn't help. MySQL already runs at <code>REPEATABLE READ</code> by default, so the first table above was this exact behaviour.</p>
<p>There's also a catch on the Postgres side. Look at those 980 errors. In the 1,000-item sale, <code>REPEATABLE READ</code> with no retry logic sold <strong>fewer than 100 of the 1,000 items</strong>, because almost every buyer who overlapped with someone got an error and gave up. You've swapped overselling for customers staring at an error page while the stock sits there. A stricter isolation level is only a fix if you also retry.</p>
<h2>Four fixes, and what they cost</h2>
<p>These are the four approaches I see recommended most. All four stopped the overselling completely on both databases. Where they differ is speed and how they behave under pressure.</p>
<h3>1. Let the database do the check: a conditional <code>UPDATE</code></h3>
<pre><code class="language-go">res, err := tx.ExecContext(ctx,
    "UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock &gt; 0", id)
if err != nil {
    return err
}

if n, _ := res.RowsAffected(); n == 0 {
    return ErrSoldOut
}
// then insert the order and commit
</code></pre>
<p>There's no separate read any more. The check (<code>stock &gt; 0</code>) and the write happen in one statement, and both databases evaluate that <code>WHERE</code> against the current row after waiting for any lock on it. When buyer B finally gets the row, the stock is already 0, the condition is false, and zero rows are updated. B gets "sold out" and nothing is written.</p>
<p>I like this one because there's nothing to remember. No isolation level to set, no retry loop, no version column. <code>stock - 1</code> also means the database does the maths, so a stale value in your Go code can't leak into the table.</p>
<h3>2. Lock the row while you decide: <code>SELECT ... FOR UPDATE</code></h3>
<pre><code class="language-go">tx.QueryRowContext(ctx,
    "SELECT stock FROM products WHERE id = $1 FOR UPDATE", id).Scan(&amp;stock)
</code></pre>
<p>This keeps the original code shape and adds two words. <code>FOR UPDATE</code> takes the row lock at read time, so buyer B's <code>SELECT</code> waits until A commits and then reads the real value.</p>
<p>This is the right choice when the decision needs more than a single comparison, for example "only if this customer hasn't bought one already" or "only if the coupon is still valid". The cost is that every buyer queues on that row for the whole transaction. Whatever you do between the <code>SELECT</code> and the commit, every other buyer waits for it. Please don't call a payment API while holding that lock.</p>
<h3>3. Optimistic locking: a version column</h3>
<pre><code class="language-sql">UPDATE products
SET stock = $1, version = version + 1
WHERE id = $2 AND version = $3
</code></pre>
<p>Read the row with its <code>version</code>, and only write if the version hasn't changed. If zero rows were updated, someone got there first, so you start again.</p>
<p>Most ORMs support this out of the box, and it's great when conflicts are rare, like two admins editing the same product description. It is not great for one hot row. In the 1,000-item sale, Postgres needed about 4,600 retries. MySQL needed about 48,800, and its throughput dropped to roughly 24 attempts per second, the slowest result in the whole test.</p>
<h3>4. <code>SERIALIZABLE</code> plus retries</h3>
<p>Keep the original read-then-write code, run it at <code>SERIALIZABLE</code>, and retry when the database rejects a transaction:</p>
<pre><code class="language-go">for attempt := 0; attempt &lt; maxRetries; attempt++ {
    err := buyOnce(ctx, sql.LevelSerializable)
    if !isRetryable(err) { // SQLSTATE 40001/40P01 on Postgres, error 1213 on MySQL
        return err
    }
}
</code></pre>
<p>Both databases then refuse to oversell, but in different ways. Postgres detects the conflict and fails the transaction with a serialization error. MySQL quietly turns every plain <code>SELECT</code> into a shared lock, so two buyers both hold a read lock, both try to upgrade it to write, and InnoDB kills one of them as a deadlock. I checked InnoDB's own deadlock counter after a run, and it matched my retry count exactly.</p>
<p>It's correct, and it's the most general option because it protects every query in the transaction, not just the one you remembered. On a single hot row, though, it's expensive: about 30,000 retries on Postgres and 48,000 deadlocks on MySQL for 3,000 purchase attempts.</p>
<h2>How fast is each one?</h2>
<p>Same setup as the 1,000-item sale: 3,000 attempts, 50 buyers, one product. I ran it twice and show the range of both runs.</p>
<table>
<thead>
<tr>
<th>Approach</th>
<th>Oversold</th>
<th>Postgres attempts/s</th>
<th>MySQL attempts/s</th>
<th>Retries (PG / MySQL)</th>
</tr>
</thead>
<tbody><tr>
<td>Read, check, write (default isolation)</td>
<td><strong>2,000</strong></td>
<td>128 to 160</td>
<td>84 to 85</td>
<td>0 / 0</td>
</tr>
<tr>
<td>Conditional <code>UPDATE</code></td>
<td>0</td>
<td><strong>353 to 443</strong></td>
<td><strong>169 to 198</strong></td>
<td>0 / 0</td>
</tr>
<tr>
<td><code>SELECT ... FOR UPDATE</code></td>
<td>0</td>
<td>214 to 223</td>
<td>136 to 191</td>
<td>0 / 0</td>
</tr>
<tr>
<td>Version column + retry</td>
<td>0</td>
<td>202 to 221</td>
<td>23 to 25</td>
<td>~4,600 / ~48,800</td>
</tr>
<tr>
<td><code>SERIALIZABLE</code> + retry</td>
<td>0</td>
<td>89 to 90</td>
<td>33 to 36</td>
<td>~30,000 / ~48,000</td>
</tr>
</tbody></table>
<p>A few honest caveats:</p>
<ul>
<li>This ran on my laptop, with Docker Desktop on Windows and default database settings. Every commit waits for a disk flush, which is why the absolute numbers are low. <strong>Compare the rows with each other</strong>, not with your production database.</li>
<li>It's one very hot row on purpose. With thousands of different products and buyers spread across them, conflicts are rare and the differences shrink a lot.</li>
<li>The broken version isn't even fast. It was slower than the conditional <code>UPDATE</code> on both databases, because it does an extra round trip and still has to queue for the row lock on its <code>UPDATE</code>.</li>
</ul>
<h2>So which one should you use?</h2>
<p>Here's how I'd pick now:</p>
<ul>
<li><strong>Decrementing a counter (stock, seats, credits, coupon uses)?</strong> Conditional <code>UPDATE</code>. It was the fastest and the simplest in every run.</li>
<li><strong>Need to check several things before deciding?</strong> <code>SELECT ... FOR UPDATE</code>, and keep that transaction short.</li>
<li><strong>Users editing records that rarely collide?</strong> Version column. That's what it's built for.</li>
<li><strong>Complex transactions where you can't list every risky read?</strong> <code>SERIALIZABLE</code> with a retry loop, and make sure the retried work is safe to repeat.</li>
</ul>
<p>And whatever you pick, add <code>CHECK (stock &gt;= 0)</code> anyway. It wouldn't have caught the original bug, but it will catch the next person who writes <code>stock = stock - 1</code> without the <code>WHERE stock &gt; 0</code>.</p>
<p>If a single product is getting tens of thousands of purchases per second, no amount of row locking will keep up, and that's when people move the counter into something like Redis with an atomic decrement in front of the database. I wrote about building exactly that kind of atomic counter in Go in my <a href="https://rimazsaththar.hashnode.dev/1-200-requests-through-a-limit-of-100-building-a-distributed-rate-limiter-in-go">previous article on distributed rate limiting</a>. It's the same bug in a different place.</p>
<h2>What I learned</h2>
<ol>
<li><strong>A transaction is not a lock.</strong> Wrapping read-check-write in <code>BEGIN</code> and <code>COMMIT</code> made it feel safe, and on the default settings of both databases it protected nothing.</li>
<li><strong>The same isolation level name means different things.</strong> <code>REPEATABLE READ</code> stopped the oversell on Postgres and did nothing on MySQL. If your code relies on isolation behaviour, test it on the database you actually run.</li>
<li><strong>Stricter isolation moves the problem.</strong> Without retries, Postgres went from overselling to selling fewer than 100 of 1,000 items.</li>
<li><strong>Push the decision into the write.</strong> The safest version was also the shortest: let the <code>WHERE</code> clause do the check at the moment the row is locked.</li>
<li><strong>Concurrency bugs need concurrent tests.</strong> None of this shows up with one request at a time. Fifty goroutines and a closed channel found it in under a second.</li>
</ol>
<hr />
<p>The full experiment is about 300 lines of Go with Postgres and MySQL in Docker, so you can run it yourself and try other isolation levels: <a href="https://github.com/Rimaz17/last-item-race">github.com/Rimaz17/last-item-race</a></p>
<p>If you've hit this in production, I'd love to hear how you found it. Mine was found by a test I wrote on purpose, which is the cheap way to find it.</p>
]]></content:encoded></item><item><title><![CDATA[1,200 Requests Through a Limit of 100: Building a Distributed Rate Limiter in Go]]></title><description><![CDATA[A Redis GET-then-SET let 1,200 requests through a limit of 100. How I built a correct distributed rate limiter in Go with an atomic Lua script.]]></description><link>https://rimazsaththar.hashnode.dev/1-200-requests-through-a-limit-of-100-building-a-distributed-rate-limiter-in-go</link><guid isPermaLink="true">https://rimazsaththar.hashnode.dev/1-200-requests-through-a-limit-of-100-building-a-distributed-rate-limiter-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Redis]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[Backend Development]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Rimaz Saththar]]></dc:creator><pubDate>Mon, 30 Nov 2026 08:02:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/3c47f90e-3990-4099-8090-a668a459bfc3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>TL;DR</strong></p>
<ul>
<li>Rate limiting with an in-memory counter stops working the moment you run more than one instance. Each instance counts on its own, so three instances allow three times the limit.</li>
<li>Moving the counter into Redis isn't enough on its own. A read-then-write version let <strong>1,200 of 1,200</strong> requests through a limit of 100 in my test.</li>
<li>The fix: one Lua script that reads, refills and takes a token in a single atomic step, using Redis's clock. Same test: <strong>exactly 100 of 1,200</strong>.</li>
<li>When Redis goes down, a circuit breaker switches each instance to a smaller local limit instead of letting everything through.</li>
<li>About <strong>1 ms</strong> per decision at the median. Code: <a href="https://github.com/Rimaz17/RateGuard">github.com/Rimaz17/RateGuard</a>.</li>
</ul>
</blockquote>
<p>When an application runs on a single server, rate limiting is easy. You keep a counter in memory, add one for each request, and refuse requests once the counter passes the limit.</p>
<p>The trouble starts when you add a second server. I wanted to understand that problem properly, so I built <strong>RateGuard</strong>: a standalone rate-limiting service in Go. Your application asks it over HTTP, "should I allow this request?", and it answers yes or no. In this article I'll walk through the problems I ran into making that answer correct across several instances, and the decisions I made along the way.</p>
<h2>The problem: three servers, three limits</h2>
<p>Here's the setup I used to test it. One client has a limit of <strong>100 requests an hour</strong>. Three RateGuard instances sit behind an nginx load balancer, and the client sends <strong>300 requests at once</strong>.</p>
<p>With a normal in-memory limiter, this is what my integration test printed:</p>
<pre><code class="language-plaintext">300 requests in 110ms: 300 allowed, 0 refused; instances served [100 100 100]
</code></pre>
<p>Every single request was allowed. The load balancer spread the 300 requests evenly, so each instance saw 100. Each instance had its own counter with its own limit of 100, so each one happily allowed all of them. The client got three times its limit, and nothing looked wrong from inside any one instance.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/22cb44b2-e0d9-42c6-8bd4-13c7069af4a6.png" alt="Three instances with their own in-memory counters allow 300 requests, while three instances sharing one Redis bucket allow exactly 100" style="display:block;margin:0 auto" />

<p>The fix sounds obvious: keep the counter in one place that every instance can see. I used Redis.</p>
<h2>The obvious Redis version, and why it breaks</h2>
<p>My first thought was to read the counter from Redis, check it, and write it back:</p>
<pre><code class="language-go">func naiveTake(ctx context.Context, rdb *redis.Client) bool {
	tokens, _ := rdb.Get(ctx, key).Int()
	if tokens &gt; 0 {
		rdb.Set(ctx, key, tokens-1, 0)
		return true
	}
	return false
}
</code></pre>
<p>Before going further, I wanted to see how badly this could go wrong, so I wrote a small test. Three Redis clients (standing in for three instances), 16 workers each, 1,200 attempts in total, on a bucket of 100 tokens. I ran it five times:</p>
<pre><code class="language-plaintext">naive  allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 48
naive  allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 45
naive  allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 46
naive  allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 43
naive  allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 46
</code></pre>
<p>It allowed <strong>every request</strong>, and Redis still thought there were about 45 tokens left.</p>
<p>The problem is the gap between <code>GET</code> and <code>SET</code>. With 48 workers running at once, many of them read the same value before any of them writes. Here's what that looks like with just three:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/06ea3bc4-1489-4e4b-8687-743b31c3a8ed.png" alt="Timeline of three instances reading 100 from Redis before writing 99, so three requests are allowed but only one token is removed" style="display:block;margin:0 auto" />

<p>Three requests were allowed, but the counter only went down by one. This is called a <em>lost update</em>, and under enough concurrency it happens on almost every request. Each command is atomic on its own, but the read-check-write sequence as a whole is not.</p>
<h2>Choosing how to make it atomic</h2>
<p>I looked at three ways to fix it:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>How it works</th>
<th>Why I did or didn't use it</th>
</tr>
</thead>
<tbody><tr>
<td><code>INCR</code> with a fixed window</td>
<td>Increment a counter per minute or hour; refuse when it's over the limit</td>
<td>Atomic, but it isn't a token bucket. A client can send its whole limit at the end of one window and again at the start of the next.</td>
</tr>
<tr>
<td><code>WATCH</code> / <code>MULTI</code></td>
<td>Optimistic locking: the write fails if the key changed, and you retry</td>
<td>Correct, but under heavy contention on one key most attempts fail and retry, which is exactly when you need speed</td>
</tr>
<tr>
<td>A Lua script</td>
<td>Redis runs the whole script as one step, and nothing else runs on that key in between</td>
<td>Atomic, one round trip, and the whole token-bucket logic lives in one place</td>
</tr>
</tbody></table>
<p>I went with the Lua script. Before showing it, here's the algorithm it runs.</p>
<h2>The token bucket, in plain terms</h2>
<p>Picture a bucket that holds up to <code>capacity</code> tokens. Each request takes one token. If the bucket is empty, the request is refused. Tokens drip back in at a steady rate, for example 100 an hour, until the bucket is full again.</p>
<p>This allows short bursts (a full bucket can serve 100 requests at once) while keeping the long-run average at the limit.</p>
<p>There's no background timer refilling anything. Instead, the bucket stores two numbers: how many tokens it had, and <em>when</em> it last refilled. On each request it works out how much time has passed and adds the tokens that would have dripped in since then. This is called <em>lazy refill</em>, and it means an idle client costs nothing at all.</p>
<h2>The Lua script</h2>
<p>Here's the core of the script, trimmed for the article. The full version, with input validation, is in <a href="https://github.com/Rimaz17/RateGuard/blob/main/internal/limiter/scripts/bucket.lua"><code>internal/limiter/scripts/bucket.lua</code></a>.</p>
<pre><code class="language-lua">local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])   -- tokens per second

-- One clock for every instance: Redis's own.
local clock = redis.call('TIME')
local now = tonumber(clock[1]) * 1000000 + tonumber(clock[2])

local state = redis.call('HMGET', KEYS[1], 'tokens', 'last_refill_us')
local tokens = capacity
local last = tonumber(state[2])

if last == nil then
  last = now                      -- never used, or expired because it was full
else
  tokens = math.min(capacity, tonumber(state[1]))
  local elapsed = now - last
  if elapsed &gt; 0 then             -- lazy refill
    tokens = math.min(capacity, tokens + elapsed / 1000000 * rate)
    last = now
  end
end

local allowed = tokens &gt;= 1 - 1e-9
if allowed then
  tokens = math.max(tokens - 1, 0)
  local ttl = math.ceil((capacity - tokens) / rate * 1000)
  redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_refill_us', last)
  redis.call('PEXPIRE', KEYS[1], math.max(1, ttl))
end

return {allowed and 1 or 0, tostring(tokens)}
</code></pre>
<p>A few decisions in here weren't obvious at first:</p>
<p><strong>It uses Redis's clock, not the server's.</strong> Lazy refill depends on the current time. If each instance passed in its own clock, a few hundred milliseconds of drift between servers would give different token counts for the same bucket, and the shared limit would quietly stop being shared. Calling <code>redis.call('TIME')</code> inside the script means there's exactly one clock. I also handle the case where that clock goes backwards: nothing refills, so no time is counted twice.</p>
<p><strong>A refused request writes nothing.</strong> Refill is calculated from the stored state each time, so leaving a refused bucket untouched gives the same answer on the next request as writing the refilled value would. The result: a client hammering the API after hitting its limit costs Redis reads only, no writes.</p>
<p><strong>The key deletes itself once the bucket is full.</strong> <code>PEXPIRE</code> is set to the moment the bucket will be full again. A missing key and a full bucket behave the same way, so expiring it changes no decision, and Redis only holds buckets that are actually in use.</p>
<p><strong>The</strong> <code>1e-9</code> <strong>tolerance.</strong> Floating-point refill can leave a bucket at 0.9999999999 tokens when it should be at exactly 1. Without the tolerance, that request would be refused for a rounding error.</p>
<h2>Calling it from Go</h2>
<p>On the Go side, go-redis's <code>Script</code> type sends the script with <code>EVALSHA</code> (just its hash) and falls back to sending the full script if Redis doesn't have it cached, for example after a restart:</p>
<pre><code class="language-go">func NewRedis(rdb redis.Scripter) *Redis {
	return &amp;Redis{rdb: rdb, script: redis.NewScript(bucketScript)}
}

reply, err := s.script.Run(ctx, s.rdb, []string{key},
	l.Capacity, strconv.FormatFloat(l.RefillRate, 'g', -1, 64), mode).Slice()
</code></pre>
<p>One detail here took me a while to notice. go-redis retries failed commands by default. Normally that's helpful, but think about what a retry means here: if the script ran and took a token, and then the <em>reply</em> got lost on the network, the retry runs the script again and takes a <strong>second</strong> token. So I turned retries off on RateGuard's Redis client. A failed call counts as a failure, and the circuit breaker (next section) decides what happens.</p>
<p>With the Lua script in place, the same 1,200-attempt test gives:</p>
<pre><code class="language-plaintext">lua    allowed  100 of 1200 attempts (capacity 100), tokens left in Redis: 0
</code></pre>
<p>Exactly 100, every run. And the three-instance test from the start of the article:</p>
<pre><code class="language-plaintext">300 requests in 432ms: 100 allowed, 200 refused; instances served [100 100 100]
</code></pre>
<p>Each instance still served 100 requests, but together they allowed exactly 100.</p>
<h2>What happens when Redis goes down?</h2>
<p>Now every decision depends on Redis, so Redis being down is a real question. There are three choices:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>What happens during an outage</th>
<th>The problem</th>
</tr>
</thead>
<tbody><tr>
<td>Fail open</td>
<td>Allow everything</td>
<td>Anyone gets unlimited access the moment Redis has a hiccup</td>
</tr>
<tr>
<td>Fail closed</td>
<td>Refuse everything</td>
<td>A rate limiter outage becomes an outage of every service behind it</td>
</tr>
<tr>
<td>Degrade to a local bucket</td>
<td>Each instance enforces a smaller limit from memory</td>
<td>Enforcement becomes approximate</td>
</tr>
</tbody></table>
<p>I went with the third, and made the other two available as a setting for anyone who prefers them.</p>
<p>A circuit breaker (<a href="https://github.com/sony/gobreaker">sony/gobreaker</a>) wraps every Redis call, and each call has a 100 ms timeout. After 5 failures in a row, the breaker opens and decisions switch to an in-memory bucket. That local bucket gets <code>capacity / N</code>, where N is the number of instances, so three instances together still roughly match the real limit. Every 5 seconds the breaker lets one request through to check whether Redis is back.</p>
<p>I tested this by killing Redis mid-test. The client had a limit of 30 and had already used 15. With Redis gone, 60 more requests went to the three instances:</p>
<pre><code class="language-plaintext">with redis down: map[200:30 429:30]
after redis returned: map[200:15 429:6]
</code></pre>
<p>Each instance's local bucket held 30 / 3 = 10, so 30 requests were allowed and 30 refused. Every request still got an answer, and nothing became unlimited. When Redis came back, its bucket still held the 15 tokens from before the outage, so exactly 15 more were allowed.</p>
<p>The degraded mode is never silent. Each degraded decision increments a Prometheus counter, and the breaker opening logs a warning. I deliberately didn't log every degraded decision, because during an outage that would mean thousands of log lines a second at exactly the moment the service is under strain. Instead it logs at most one warning every 10 seconds, with a count.</p>
<h2>How fast is it?</h2>
<p>I load-tested it with k6 on my laptop (Intel i5-10210U, 4 cores), with k6, RateGuard, Redis and PostgreSQL all on the same machine:</p>
<table>
<thead>
<tr>
<th>Test</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td>Median latency per decision</td>
<td>About <strong>1 ms</strong></td>
</tr>
<tr>
<td>One instance, 100 virtual users</td>
<td><strong>~4,900 requests/s</strong></td>
</tr>
<tr>
<td>Redis running just the bucket script on one key</td>
<td>~19,700/s</td>
</tr>
</tbody></table>
<p>Two honest caveats. First, the p99 latency ranged from 9 to 92 ms, mostly because the load generator was competing with the service for the same 4 CPU cores. Second, three instances behind nginx reached about 2,500 requests/s in total, <em>lower</em> than one instance, for the same reason: everything was sharing one laptop. Neither number says much about a real deployment across separate machines, so I've published them with that context instead of picking the best-looking one.</p>
<p>The bigger point is the hot path. A decision does one Redis call and nothing else: API keys and policies come from in-memory caches, and usage analytics are batched to Redis every second and PostgreSQL every 10 seconds, off the request path.</p>
<h2>Trade-offs I accepted</h2>
<ul>
<li><strong>One hot key has a ceiling.</strong> Redis runs scripts on a key one at a time, so a single very busy client tops out around 19,700 decisions a second on this machine. I didn't shard keys in v1. Instead, every bucket key comes from a single <code>keyFor()</code> function, so splitting a hot key into sub-buckets later means changing one function.</li>
<li><strong>Outage enforcement is approximate.</strong> If the load balancer sends one client's traffic unevenly, that client can go somewhat over or under its limit while Redis is down.</li>
<li><strong>The instance count is set by hand.</strong> The local bucket size depends on <code>RG_INSTANCE_COUNT</code>. If the deployment scales and nobody updates it, outage limits drift.</li>
</ul>
<h2>What I learned</h2>
<ol>
<li><strong>"Shared state" isn't the same as "correct state."</strong> Moving the counter into Redis fixed nothing until the read and the write happened as one step.</li>
<li><strong>Write the failing test first.</strong> The 1,200-of-1,200 result made the race real in a way reading about it never did, and it gave me a test to prove the fix.</li>
<li><strong>Think about time explicitly.</strong> As soon as more than one machine is involved, "now" is a design decision.</li>
<li><strong>Retries aren't free.</strong> Retrying something that isn't safe to repeat can turn a network blip into a wrong answer.</li>
<li><strong>Decide how you fail before you fail.</strong> Picking "degrade" over "open" or "closed" was a product decision as much as a technical one, and writing it down early made the circuit breaker code straightforward.</li>
</ol>
<p>Every design decision in RateGuard is written up as a short decision record in the repo, if you want to go deeper into any of these.</p>
<p><strong>Code:</strong> <a href="https://github.com/Rimaz17/RateGuard">github.com/Rimaz17/RateGuard</a></p>
]]></content:encoded></item><item><title><![CDATA[The OpenSSL Bug That Hid for 11 Years Behind an Ignored Return Value]]></title><description><![CDATA[How a 2015 OpenSSL refactor silently broke printing of ASN.1 ENUMERATED fields, how I traced it with git history, and the four-line fix.]]></description><link>https://rimazsaththar.hashnode.dev/the-openssl-bug-that-hid-for-11-years-behind-an-ignored-return-value</link><guid isPermaLink="true">https://rimazsaththar.hashnode.dev/the-openssl-bug-that-hid-for-11-years-behind-an-ignored-return-value</guid><category><![CDATA[openssl]]></category><category><![CDATA[C]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[open source]]></category><category><![CDATA[debugging]]></category><category><![CDATA[Git]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Rimaz Saththar]]></dc:creator><pubDate>Sun, 29 Nov 2026 19:18:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/3937aad9-6066-42b4-b961-f2516fd7a2b1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>TL;DR</strong></p>
<ul>
<li>Since 2015, OpenSSL couldn't print ASN.1 ENUMERATED fields. The output stopped mid-line, with no error and exit code 0.</li>
<li>Cause: a 2015 refactor made <code>ASN1_INTEGER_to_BN()</code> reject anything that isn't an INTEGER, but the printer still sent ENUMERATED values through it.</li>
<li>Fix: use <code>i2s_ASN1_ENUMERATED()</code> for ENUMERATED values. Four lines of C plus a regression test.</li>
<li>Status: approved by an OpenSSL committer and labelled for backport to 3.5, 4.0 and 4.1 (<a href="https://github.com/openssl/openssl/pull/33632">PR #33632</a>).</li>
</ul>
</blockquote>
<p>The bug report I picked up started with five bytes:</p>
<pre><code class="language-plaintext">30 03 0a 01 01
</code></pre>
<p>That's a complete, valid OCSP response. <code>30 03</code> is a SEQUENCE that's 3 bytes long, and <code>0a 01 01</code> is an ENUMERATED with the value 1. That one field is <code>responseStatus</code>. When you ask OpenSSL to print it, you get this:</p>
<pre><code class="language-plaintext">OCSP_RESPONSE:
  responseStatus: rc=0
</code></pre>
<p>The <code>rc=0</code> is from my shell, not OpenSSL. OpenSSL printed <code>responseStatus:</code> and then stopped, in the middle of the line, and exited as if everything had gone fine.</p>
<p>I'd been looking for an issue to work on in OpenSSL, and this one, <a href="https://github.com/openssl/openssl/issues/33494">#33494</a>, had been triaged by the maintainers and labelled <em>help wanted</em>. It looked small. It turned out to be a regression that had been sitting in every OpenSSL release since 1.1.0, and tracking it down taught me a lot about how bugs survive in mature code.</p>
<h2>A failure that doesn't look like one</h2>
<p>The first thing I did was reproduce it:</p>
<pre><code class="language-bash">printf '\x30\x03\x0a\x01\x01' &gt; ocspresp.der
openssl asn1parse -inform DER -in ocspresp.der -item OCSP_RESPONSE; echo "rc=$?"
</code></pre>
<p>Same result: half a line of output, nothing on stderr, exit code 0. The correct output should have been:</p>
<pre><code class="language-plaintext">OCSP_RESPONSE:
  responseStatus: 1
  responseBytes: &lt;ABSENT&gt;
</code></pre>
<p>The exit code was the first clue to why this had gone unnoticed. In <code>apps/asn1parse.c</code>, the call that does the printing throws its result away:</p>
<pre><code class="language-c">ASN1_item_print(bio_out, value, 0, it, NULL);
ASN1_item_free(value, it);
</code></pre>
<p><code>ASN1_item_print()</code> was returning 0 to say it had failed. Nobody was listening. So any script, CI job or person running this command would see success unless they read the output closely and noticed it was incomplete.</p>
<p>Without <code>-item</code>, OpenSSL's generic parser printed the same field correctly as <code>ENUMERATED :01</code>. So the data was fine. Only the structured printer was broken, and only for one type. I tried an attribute certificate (<code>X509_ACERT</code>), which also contains an ENUMERATED field, and it failed the same way. Everything after the first ENUMERATED field just vanished.</p>
<h2>Following the number down</h2>
<p>ASN.1 has two types for whole numbers: INTEGER and ENUMERATED. They're encoded identically. The only difference is the tag byte (<code>0x02</code> for INTEGER, <code>0x0a</code> for ENUMERATED) and what they mean. An ENUMERATED is a number picked from a fixed list, like a status code. Inside OpenSSL, both are stored in the same <code>ASN1_STRING</code> struct, and the <code>type</code> field tells you which one you have: <code>V_ASN1_INTEGER</code> or <code>V_ASN1_ENUMERATED</code>.</p>
<p>In <code>crypto/asn1/tasn_prn.c</code>, the printer treats them as the same thing:</p>
<pre><code class="language-c">case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
    ret = asn1_print_integer(out, str);
    break;
</code></pre>
<p><code>asn1_print_integer()</code> converts the value to a decimal string with <code>i2s_ASN1_INTEGER()</code>. That function turns the value into a <code>BIGNUM</code> first, using <code>ASN1_INTEGER_to_BN()</code>. And that's where it stops:</p>
<pre><code class="language-c">static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn, int itype)
{
    if ((ai-&gt;type &amp; ~V_ASN1_NEG) != itype) {
        ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_INTEGER_TYPE);
        return NULL;
    }
    ...
}

BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
{
    return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
}
</code></pre>
<p><code>ASN1_INTEGER_to_BN()</code> passes <code>V_ASN1_INTEGER</code> as the type it expects. Our value's type is <code>V_ASN1_ENUMERATED</code>, so the check fails, an error is raised, and <code>NULL</code> comes back up the chain.</p>
<p>The whole path looks like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0c13f11cbb1c333107724e/085b4bb2-ae26-408a-b21f-3acd44d08d6b.png" alt="Call chain from asn1_primitive_print() down to ASN1_INTEGER_to_BN(), where ENUMERATED values are rejected" style="display:block;margin:0 auto" />

<p>One layer says the two types are interchangeable. A layer three calls below says they aren't. An ENUMERATED value gets sent down the INTEGER road and is turned away at the end of it.</p>
<h2>Was it always like this?</h2>
<p>That contradiction bothered me. Code that has been printing certificates and OCSP responses for decades doesn't usually have a whole data type that just doesn't work. Either nobody had ever printed an ENUMERATED field with this function, or something had changed underneath it.</p>
<p>The strict check raises a specific error code, <code>ASN1_R_WRONG_INTEGER_TYPE</code>, so I asked git when that error code first appeared in the file:</p>
<pre><code class="language-bash">git log -S"ASN1_R_WRONG_INTEGER_TYPE" --format='%h %ad %s' --date=short -- crypto/asn1/a_int.c
</code></pre>
<pre><code class="language-plaintext">6c5b6cb035 2015-05-15 ASN1 INTEGER refactor.
</code></pre>
<p>One commit, from May 2015. Here's what <code>ASN1_INTEGER_to_BN()</code> looked like just before it:</p>
<pre><code class="language-c">BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
{
    BIGNUM *ret;

    if ((ret = BN_bin2bn(ai-&gt;data, ai-&gt;length, bn)) == NULL)
        ASN1err(ASN1_F_ASN1_INTEGER_TO_BN, ASN1_R_BN_LIB);
    else if (ai-&gt;type == V_ASN1_NEG_INTEGER)
        BN_set_negative(ret, 1);
    return (ret);
}
</code></pre>
<p>No type check at all. It converted whatever bytes it was given. The printer had been quietly relying on that since the printing code was written in 2005. The 2015 refactor tightened the rule, which was a reasonable thing to do, and the printer broke without anyone noticing. OpenSSL 1.1.0, released in 2016, was the first release with the bug. Because the failure was silent, it stayed that way through 3.x and into the 4.x branches.</p>
<p>I want to be fair to everyone involved here. Neither change was careless. The type check is a good idea, and the printer's shortcut was harmless when it was written. The bug only existed in the gap between them.</p>
<h2>The fix</h2>
<p>I had two options:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>Why I did or didn't choose it</th>
</tr>
</thead>
<tbody><tr>
<td>Loosen the type check in <code>asn1_string_to_bn()</code></td>
<td>Undoes a deliberate safety improvement and affects every caller in the library</td>
</tr>
<tr>
<td>Make the printer use the right conversion</td>
<td>Only touches the code that made the wrong assumption</td>
</tr>
</tbody></table>
<p>I went with the second. <code>i2s_ASN1_ENUMERATED()</code> already existed, so I didn't need any new conversion code:</p>
<pre><code class="language-diff"> static int asn1_print_integer(BIO *out, const ASN1_INTEGER *str)
 {
     char *s;
     int ret = 1;
-    s = i2s_ASN1_INTEGER(NULL, str);
+    if ((str-&gt;type &amp; ~V_ASN1_NEG) == V_ASN1_ENUMERATED)
+        s = i2s_ASN1_ENUMERATED(NULL, str);
+    else
+        s = i2s_ASN1_INTEGER(NULL, str);
     if (s == NULL)
         return 0;
</code></pre>
<p>The <code>&amp; ~V_ASN1_NEG</code> part matters. OpenSSL doesn't store the sign of a number separately. It sets a <code>V_ASN1_NEG</code> flag inside the type, so a negative ENUMERATED has the type <code>V_ASN1_NEG_ENUMERATED</code>, not <code>V_ASN1_ENUMERATED</code>. Without the mask, a negative value would fail the comparison and still go down the wrong path.</p>
<p>After the fix:</p>
<pre><code class="language-plaintext">OCSP_RESPONSE:
  responseStatus: 1
  responseBytes: &lt;ABSENT&gt;
</code></pre>
<h2>Testing it</h2>
<p>I added a regression test to <code>test/recipes/04-test_asn1_parse.t</code> that runs <code>asn1parse</code> on the 5-byte response and checks for <strong>both</strong> output lines:</p>
<pre><code class="language-perl">ok(grep(/^\s+responseStatus: 1$/, @out)
   &amp;&amp; grep(/^\s+responseBytes: &lt;ABSENT&gt;$/, @out),
   "asn1parse -item prints an ENUMERATED field");
</code></pre>
<p>Checking only <code>responseStatus: 1</code> wouldn't be enough. The original bug cut off everything after the ENUMERATED field, so a test that ignored the next line could pass while the rest of the structure was still missing.</p>
<table>
<thead>
<tr>
<th>What I checked</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td>New test, without the fix</td>
<td>Fails</td>
</tr>
<tr>
<td>New test, with the fix</td>
<td>Passes</td>
</tr>
<tr>
<td>Full <code>make test</code> with ASan and UBSan</td>
<td>Passes, no sanitizer reports</td>
</tr>
<tr>
<td>Negative ENUMERATED (<code>-1</code>)</td>
<td>Prints <code>-1</code></td>
</tr>
<tr>
<td>Existing <code>ocsp-response.der</code> in the test suite</td>
<td>Prints correctly</td>
</tr>
<tr>
<td>INTEGER fields (e.g. certificate serial numbers)</td>
<td>Unchanged</td>
</tr>
</tbody></table>
<h2>What happened next</h2>
<p>I opened <a href="https://github.com/openssl/openssl/pull/33632">PR #33632</a>. An OpenSSL committer reviewed and approved it, and it was labelled for backport to the 3.5, 4.0 and 4.1 branches. At the time of writing it's waiting on a second approval before it's merged.</p>
<p>The review was useful in its own right. The reviewer said they'd personally prefer a separate <code>asn1_print_enumerate()</code> function, but that it probably wasn't worth the churn. I think that's the right call for a fix heading into three stable branches: a smaller diff is easier to review and backport. They also pointed out that the test could feed the bytes through stdin instead of writing a file. Both were fair points, and I learned more from those two comments about how OpenSSL is maintained than from reading the code.</p>
<p>There's one related change I left out on purpose. <code>asn1parse</code> still ignores the return value of <code>ASN1_item_print()</code>. Fixing that would change how the command behaves, so I mentioned it in the PR rather than slipping it into a bug fix.</p>
<h2>What I'm taking away</h2>
<p>The fix was four lines. Finding out why those four lines were needed was the actual work, and a few things stuck with me:</p>
<ul>
<li><strong>Ignored return values hide bugs for years.</strong> If <code>asn1parse</code> had checked one return value, this would most likely have been caught years earlier.</li>
<li><strong>Making a check stricter can break code far away.</strong> When I tighten validation now, I look for callers that might depend on the looser behaviour.</li>
<li><code>git log -S</code> <strong>answers "when did this start?"</strong> Searching for when a specific error code appeared took me straight to the commit.</li>
<li><strong>Fix where the mistake is, not where it hurts.</strong> The failure showed up deep in a conversion function, but the real problem was the printer's assumption.</li>
</ul>
<p>If you've been wanting to contribute to a big open-source project, look for a <em>help wanted</em> label, comment before you start, and keep your first PR small. Mine started with five bytes.</p>
<p><strong>Links:</strong> <a href="https://github.com/openssl/openssl/issues/33494">Issue #33494</a> · <a href="https://github.com/openssl/openssl/pull/33632">PR #33632</a></p>
]]></content:encoded></item></channel></rss>