<?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 Mohitkumar on Medium]]></title>
        <description><![CDATA[Stories by Mohitkumar on Medium]]></description>
        <link>https://medium.com/@mohitkumar4922251?source=rss-1bc3b8ad4f49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aLcxTbxQmDObqyWZl3Xc_w.png</url>
            <title>Stories by Mohitkumar on Medium</title>
            <link>https://medium.com/@mohitkumar4922251?source=rss-1bc3b8ad4f49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:05:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohitkumar4922251/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[My IDE Yelled at My `@Autowired` — It Was Right]]></title>
            <link>https://medium.com/@mohitkumar4922251/my-ide-yelled-at-my-autowired-it-was-right-43241dd13976?source=rss-1bc3b8ad4f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/43241dd13976</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[autowired]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Mohitkumar]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 02:12:45 GMT</pubDate>
            <atom:updated>2026-09-15T02:12:45.337Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>My IDE Yelled at My `@Autowired` — It Was Right</strong></p><p><strong>Eight yellow squiggles, zero broken tests, and the afternoon I stopped writing field injection.</strong></p><p>I was building VideoScale, a distributed video transcoding pipeline (Spring Boot</p><p>+ Kafka + MinIO + Postgres), when I noticed yellow squiggles all over my</p><p>controllers. Eight of them, across five classes. Every single one sat on top of</p><p>a `@Autowired` field.</p><p>Nothing was broken. Uploads worked, jobs processed, tests passed. That’s exactly</p><p>why I almost ignored them — and exactly why you shouldn’t.</p><p><strong>The code every tutorial taught me</strong></p><p>This is my actual `VideoController` before the fix:</p><pre>@RestController<br>@RequestMapping(&quot;/api/videos&quot;)<br>public class VideoController {<br><br>@Autowired<br>private VideoStorageService storageService;<br>@Autowired<br>private KafkaProducerService kafkaProducerService;<br>@Autowired<br>private VideoJobRepository videoJobRepository;<br><br>// …<br>}</pre><p>If you’ve written Spring, you’ve written this. It’s in nearly every tutorial</p><p>because it optimizes for one thing: seeing it work in five minutes. Two lines</p><p>per dependency, no constructor to maintain. I copied it without a single</p><p>thought — and I’d bet most of us did.</p><p><strong>Three things wrong with code that works</strong></p><p>Lets frame it precisely: the annotation isn’t the problem, the <em>*placement*</em> is. On a field, `@Autowired` uses reflection to set a private attribute, and that costs</p><p>you three things:</p><p><strong>1. Your dependencies go invisible.</strong> Nothing in the class’s public contract</p><p>says “I need storage, Kafka, and a repository to function.” A new teammate (or future you) must read the field list to discover what the object needs. The constructor — the one place Java guarantees runs before the object exists — says nothing.</p><p><strong>2. You can’t build the object yourself.</strong> This is the one that converted me:</p><pre>// Compiles. Then dies with NullPointerException.<br>var controller = new VideoController();</pre><p>Three null fields, zero warnings from the compiler. The only ways to fill them are a running Spring container or reflection hacks — meaning a “unit” test for</p><p>this plain class needs a framework to exist. That’s backwards.</p><p><strong>3. Nothing is final.</strong> The fields can be reassigned after construction. Your</p><p>object is never provably fully-initialized; it’s fully-initialized by</p><p>convention, and conventions are exactly what break at 2 AM.</p><p><strong>The after: no annotation at all</strong></p><pre>public class VideoController {<br>  private final VideoStorageService storageService;<br>  private final KafkaProducerService kafkaProducerService;<br>  private final VideoJobRepository videoJobRepository;<br><br>  public VideoController(VideoStorageService storageService,<br>                         KafkaProducerService kafkaProducerService,<br>                         VideoJobRepository videoJobRepository) {<br>      this.storageService = storageService;<br>      this.kafkaProducerService = kafkaProducerService;<br>      this.videoJobRepository = videoJobRepository;<br>}<br><br>// .....<br><br>}</pre><p>Since Spring 4.3, a single constructor is used for injection automatically —</p><p>`@Autowired` on it would be pure noise. Three parameters, three `final` fields, impossible to construct half-broken. And the test that was impossible before:</p><pre>var controller = new VideoController(mockStorage, mockProducer, mockRepo);</pre><p>No context. No reflection. No Spring. Just Java.</p><p><strong>The takeaway I keep</strong></p><p>I didn’t fix a bug that day. I fixed eight <em>*future*</em> bugs — the kind where I add</p><p>a fourth dependency in three months, write a test without the container, and spend an afternoon staring at nulls.</p><p>Here’s my rule now: <strong>the compiler proves syntax; the IDE hints at design.</strong></p><p>Yellow squiggles are the only feedback loop a solo developer has for code that runs but lies. I treat the Problems panel as a todo list, not wallpaper.</p><p>What’s the warning you’ve been ignoring? It’s probably right too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43241dd13976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI Twitter Bot That Runs Itself for Less Than a Penny a Month]]></title>
            <link>https://medium.com/@mohitkumar4922251/i-built-an-ai-twitter-bot-that-runs-itself-for-less-than-a-penny-a-month-cc2a6ac378cd?source=rss-1bc3b8ad4f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2a6ac378cd</guid>
            <category><![CDATA[post]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Mohitkumar]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 01:36:26 GMT</pubDate>
            <atom:updated>2026-08-06T01:36:26.416Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical build story about AWS CDK, OpenAI, Twitter’s API, and the bugs hiding in the last mile of automation.</em></p><p>TL;DR: I built a scheduled, serverless bot that uses AWS Lambda, OpenAI, and Twitter API v2 to publish a developer tweet every Monday for almost no infrastructure cost.</p><p>I kept making the same promise to myself: post something useful for developers every week.</p><p>The promise usually lasted until the week got busy.</p><p>Writing one short post was never the hard part. Remembering to write it, checking the character count, choosing a topic, and publishing it on schedule turned a small habit into another task on my list.</p><p>So I built a small serverless bot to handle the routine.</p><p>Every Monday at 3:30 PM IST, an AWS EventBridge rule triggers a Node.js 20 Lambda function in the Mumbai region. The function loads its secrets, asks GPT-4o-mini for a developer-focused tweet, checks that the result stays under Twitter’s 280-character limit, and publishes it through Twitter API v2.</p><p>The AWS infrastructure costs about $0.00 per month within the free tier. OpenAI costs roughly $0.0004 per tweet at the current prompt size. SSM Parameter Store API calls are free for Standard parameters, so the five secret reads per weekly run add nothing to the bill.</p><p>That sounds simple. The final handler is short. The difficult part lived in initialization order, token permissions, and infrastructure state.</p><h3>The architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzMRuZPCIW1lzSq-Yd83xg.png" /></figure><p>The production flow has five parts:</p><p>1. EventBridge triggers the Lambda every Monday at 3:30 PM IST.</p><p>2. Lambda reads encrypted values from AWS Systems Manager Parameter Store.</p><p>3. OpenAI generates a short developer tweet.</p><p>4. The handler rejects empty output or anything longer than 280 characters.</p><p>5. Twitter API v2 publishes the tweet.</p><p>The project uses TypeScript, AWS CDK v2, esbuild, pnpm, and Node.js 20. Lambda runs with 128 MB of memory and a 90-second timeout. Its IAM policy only grants `ssm:GetParameter` for the `/twitter-bot/*` parameter path.</p><p>The full source is available at [github.com/Zyrexam/serverless-twitter-bot](https://github.com/Zyrexam/serverless-twitter-bot).</p><p>The repository also includes a SourceCodeShots integration. SourceCodeShots is an API that turns source code into styled PNG images for sharing. I left that integration disabled in the current scheduled handler while the text-only flow remains the stable path. The image workflow can be enabled without changing the scheduling or secret-management design.</p><h3>The first design decision: keep credentials out of the stack</h3><p>The bot needs five secrets:</p><ul><li>OPENAI_API_KEY</li><li>CONSUMER_KEY</li><li>CONSUMER_KEY_SECRET</li><li>ACCESS_KEY</li><li>ACCESS_KEY_SECRET</li></ul><p>I store them as SSM SecureString parameters instead of putting real values into Lambda environment variables.</p><p>CloudFormation rejected my first attempt with an error about SSM secure references. That refusal is useful. A decrypted secret should not end up in CloudFormation metadata just because a Lambda needs it.</p><p>The Lambda fetches each value at runtime:</p><pre>const command = new GetParameterCommand({<br>  Name: parameterName,<br>  WithDecryption: true,<br>});<br><br>const response = await ssmClient.send(command);<br>return response.Parameter?.Value || &#39;&#39;;</pre><p>The handler calls loadSecrets() before it asks OpenAI or Twitter to do anything. Locally, the project reads values from .env; inside Lambda, it loads the encrypted parameters from SSM.</p><h3>The bug that explained the whole system</h3><p>My first production failure looked like an authentication problem:</p><pre>401 Incorrect API key provided: PLACEHOLDER</pre><p>The real key existed in SSM. The Lambda had fetched it. I still got the placeholder.</p><p>The reason was initialization order. I had created the OpenAI client at module load time, before the handler loaded the secrets. The client captured the placeholder value and kept using it.</p><p>The fix was lazy initialization:</p><pre>let openaiClient: OpenAI | null = null;<br><br>function getClient(): OpenAI {<br>  if (!openaiClient) {<br>    const apiKey = process.env.OPENAI_API_KEY;<br><br>    if (!apiKey || apiKey === &#39;PLACEHOLDER&#39;) {<br>      throw new Error(&#39;OPENAI_API_KEY is missing&#39;);<br>    }<br><br>    openaiClient = new OpenAI({ apiKey, timeout: 10000 });<br>  }<br><br>  return openaiClient;<br>}</pre><p>The Twitter client follows the same pattern. When credentials arrive at runtime, create clients after the credentials arrive.</p><h3>The token that refused to learn</h3><p>After fixing the secret-loading bug, Twitter returned a different failure:</p><pre>403<br>x-access-level: read</pre><p>The app settings showed Read and write permissions, so I assumed the code was wrong. It was not.</p><p>Twitter tokens are snapshots of the permissions available when they were generated. Changing the app permissions does not upgrade an old token. I had to save the new permissions, generate fresh access tokens, and confirm that the generated credentials belonged to a Read and write configuration.</p><p>The lesson is easy to miss: change permissions first, then create tokens. Check the token’s access level before debugging the request code.</p><h3>A billing error wearing a developer costume</h3><p>One test reached Twitter successfully, authenticated correctly, and then failed with:</p><pre>402 Payment Required, credits depleted</pre><p>That was not an API integration bug. It was an exhausted posting allowance. Rewriting the OAuth code would not have helped.</p><p>The useful fix was better logging. For a failed post, the bot records the error message, code, HTTP status, response data, and headers. A log entry such as `status: 402` with `message: “credits depleted”` makes the billing condition clear instead of leaving an unexplained crash.</p><p>External limits belong in the operating model of an automation project. A passing unit test cannot tell you whether a provider still has credits.</p><h3>The infrastructure mistake I should have avoided</h3><p>At one point, I deleted a Lambda resource manually from the AWS console. CloudFormation still believed it owned that resource, so the stack became stuck in DELETE_FAILED.</p><p>The recovery involved retrying the deletion and retaining the orphaned policy. The cleaner solution would have been to use the project command:</p><pre>pnpm cdk:destroy</pre><p>When infrastructure comes from code, its lifecycle should come from code too. Manual console edits create state that the next deployment has to explain.</p><h3>The smaller bugs still mattered</h3><p>The larger failures got the headlines, but several small problems also shaped the design:</p><ul><li>A tweet longer than 280 characters was rejected by the handler before Twitter saw it.</li><li>A missing model name led me to check the account’s available models and use gpt-4o-mini.</li><li>Missing pnpm binary links made tsc appear unavailable until the dependencies were reinstalled.</li><li>A malformed package.json broke the toolchain before the application code ran.</li><li>Windows process behavior made explicit exit handling less reliable than returning a failed promise and setting the exit code.</li></ul><p>None of these problems required a large framework. They required clear boundaries and useful error messages.</p><h3>Run the project locally</h3><p>Install the dependencies and build the TypeScript project:</p><pre>git clone https://github.com/Zyrexam/serverless-twitter-bot.git<br>cd serverless-twitter-bot<br>pnpm install<br>pnpm build</pre><p>For local execution, create a `.env` file with the five credentials listed above and run:</p><pre>pnpm post-tweet</pre><p>For AWS deployment, configure the CLI, bootstrap CDK once in `ap-south-1`, create the SSM parameters under `/twitter-bot/`, and deploy:</p><pre>aws configure<br>npx cdk bootstrap aws://ACCOUNT_ID/ap-south-1<br>pnpm cdk:deploy</pre><p>To remove the stack later, use:</p><pre>pnpm cdk:destroy</pre><p>Once the bot is deployed and posting reliably, the next improvements are about memory, observability, and avoiding duplicate content.</p><h3>What I would add next</h3><p>The bot is stateless. It does not remember which tweets it has already posted, so duplicate prevention would need a small DynamoDB table containing tweet hashes or generated-content IDs.</p><p>I would also add a dry-run mode, provider-aware retry handling, and a metric for successful posts, rejected posts, and exhausted credits. Those additions would make the bot easier to trust over months rather than days.</p><p>The main surprise was not that a few lines of code could publish a tweet. It was how much reliability came from the surrounding decisions: load secrets at the right time, initialize clients lazily, validate provider permissions, log external failures, and let infrastructure tools manage their own resources.</p><p>That is the part of automation people rarely see in a finished repository. It is also the part that keeps the repository running.</p><p><strong>What small task would you automate if it could show up for you every week?</strong></p><p>If this saved you some setup time, leave a comment or follow for more posts on serverless architecture and developer tooling. The full source is on GitHub, so feel free to fork it and extend the bot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2a6ac378cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exactly-Once, Damn It: Building a Payment Idempotency Layer]]></title>
            <link>https://medium.com/@mohitkumar4922251/exactly-once-damn-it-building-a-payment-idempotency-layer-1d21af5a718a?source=rss-1bc3b8ad4f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d21af5a718a</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[distributed-locks]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Mohitkumar]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 15:28:05 GMT</pubDate>
            <atom:updated>2026-07-10T15:28:05.736Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From a naive proxy to distributed locks, Redis caches, and SHA-256 tamper detection — in six problems.</em></p><p>I was building a payment proxy. The requirement sounded simple: a customer clicks “Pay Now” once, the charge goes through exactly once — no matter how many retries, timeouts, or duplicate requests arrive.</p><p>What started as a single FastAPI endpoint turned into Redis caches, distributed locks, Lua scripts, and SHA-256 tamper detection. Every layer was a response to a failure I didn’t see coming.</p><p>Here are the six problems, in the order I hit them.</p><h3>Problem #1: The naive proxy double-charges customers</h3><p>The first version was three lines. Accept request, forward to payment provider, return response.</p><p>Here’s the failure. A customer pays $500. Your proxy forwards it to Stripe. Stripe charges the card and sends back 200 OK. Right then, the network between your proxy and the frontend drops. The customer sees a spinner. They click Pay again. Your proxy forwards it again. The customer is now charged $1,000.</p><p>This isn’t theoretical. Payment providers like Stripe and Adyen are not idempotent by default. Send the same charge request twice, you get two charges.</p><p><strong>Fix:</strong> Every request carries an Idempotency-Key header — a UUID v4 generated by the client. Same key = same operation. Before touching the payment provider, check if you&#39;ve seen this key before.</p><pre>@app.post(&quot;/api/v1/payments&quot;)<br>async def create_payment(<br>    payment_request: PaymentRequest,<br>    idempotency_key: str = Header(..., alias=&quot;Idempotency-Key&quot;),<br>):<br>    if not validate_uuid(idempotency_key):<br>        raise HTTPException(status_code=400, detail=&quot;Invalid Idempotency-Key format&quot;)<br><br>    status_code, response_body = await idempotency_service.process_payment(<br>        idempotency_key, request_body=payment_request.model_dump_json(),<br>        payment_processor=mock_payment_provider<br>    )<br>    return JSONResponse(status_code=status_code, content=json.loads(response_body))</pre><p><strong>Trade-off:</strong> The client must generate and store the key. A weak key (timestamp-based) risks collisions.</p><h3>Problem #2: Checking the database isn’t enough</h3><p>My first attempt: query PostgreSQL on every request. If a record exists, return it. If not, process and save.</p><pre>t=0ms: Request A → checks DB → no record found<br>t=0ms: Request B → checks DB → no record found (A hasn&#39;t written yet)<br>t=1ms: Request A → calls payment provider → $500 charged<br>t=1ms: Request B → calls payment provider → $500 charged again</pre><p>Both requests saw nothing at the same microsecond. Both proceeded. A unique constraint on the column doesn’t help — both pass the SELECT before either hits the INSERT.</p><p><strong>Fix:</strong> Two layers. Redis for the fast path (sub-millisecond duplicate detection). A distributed lock to serialize concurrent writes.</p><pre>async def process_payment(self, idempotency_key, request_body, payment_processor):<br>    cached = await self._get_cached_response(idempotency_key)<br>    if cached:<br>        return cached  # Fast path, ~2ms<br><br>    lock_key = f&quot;idempotency:lock:{idempotency_key}&quot;<br>    result = await self.lock_service.execute_with_lock(<br>        lock_key, execute_payment, timeout_seconds=30, fail_fast=True<br>    )</pre><p><strong>Trade-off:</strong> Redis is an extra dependency. A Redis round-trip (~1ms) beats a PostgreSQL round-trip (~5ms) at scale — worth it.</p><h3>Problem #3: The lock alone isn’t enough</h3><p>Scenario: Request A acquires the lock, creates a PROCESSING record, calls the payment provider. A crashes. The lock auto-releases after 30 seconds. Request B acquires the lock, checks the database, sees PROCESSING. What should B do?</p><p><strong>Fix:</strong> A double-check inside the locked section. Re-query the database before doing anything.</p><pre>async def execute_payment():<br>    recheck = self._get_existing_record(idempotency_key)<br>    if recheck:<br>        if recheck.status == ProcessingStatus.COMPLETED:<br>            if recheck.request_hash != request_hash:<br>                return 409, json.dumps({&quot;error&quot;: &quot;Key reused with different body&quot;})<br>            return recheck.response_status_code, recheck.response_body<br>        elif recheck.status == ProcessingStatus.PROCESSING:<br>            return 409, json.dumps({&quot;error&quot;: &quot;Request is being processed&quot;})<br><br>    record = self._create_processing_record(idempotency_key, request_body, request_hash)</pre><p><strong>Trade-off:</strong> Extra DB query inside the lock adds ~3ms. Acceptable — only runs on cache misses.</p><h3>Problem #4: The lock release bug</h3><pre># DANGER: TOCTOU race condition<br>value = await redis.get(lock_key)<br>if value == my_lock_value:<br>    await redis.delete(lock_key)</pre><p>Between GET and DEL, the lock can expire, another worker acquires it, and your DELETE nukes their lock.</p><p><strong>Fix:</strong> A Lua script that checks ownership and deletes atomically. Redis guarantees no interleaving while it runs.</p><pre>if redis.call(&quot;get&quot;, KEYS[1]) == ARGV[1] then<br>    return redis.call(&quot;del&quot;, KEYS[1])<br>else<br>    return 0<br>end</pre><pre>async def release(self, lock_key: str, lock_value: str) -&gt; bool:<br>    script = await self._get_script()  # registered once, cached<br>    result = await script(keys=[lock_key], args=[lock_value])<br>    return bool(result)</pre><p><strong>Trade-off:</strong> Lua blocks Redis while executing. Our script is 5 lines, completes in microseconds — safe.</p><h3>Problem #5: Same key, different body</h3><p>The naive assumption: duplicate key = identical operation. Just return the stored response.</p><p>Wrong. A customer initiates a $100 payment. Network times out. They retry — but their cart changed, amount is now $200. The key is a promise: “this is the same operation.” Different body = different operation.</p><p><strong>Fix:</strong> SHA-256 hash the request body. Store it with the record. On duplicate key, compare hashes.</p><pre>def _hash_request(self, body: str) -&gt; str:<br>    return hashlib.sha256(body.encode()).hexdigest()<br>if existing.request_hash != request_hash:<br>    return 409, json.dumps({&quot;error&quot;: &quot;Idempotency key reused with different request body&quot;})</pre><p>Verified end-to-end: send amount=$100, retry same key with amount=$200, get back the original $100 response. The $200 is silently ignored.</p><p><strong>Trade-off:</strong> SHA-256 on a small JSON body adds &lt;10μs. Negligible.</p><h3>Problem #6: What happens when Redis dies</h3><p>Redis lives entirely in memory. If it restarts, everything disappears — locks and cached responses included.</p><p>Failure scenario: Request A holds the lock, has a PROCESSING record in PostgreSQL, is mid-call to the payment provider. Redis crashes. Lock disappears. Request B arrives, cache is down, checks PostgreSQL, sees PROCESSING, returns 409. No double charge.</p><p><strong>Fix:</strong> PostgreSQL is the durable source of truth. Redis is the performance layer, not the guarantee.</p><pre>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    redis_ok = await redis_connected()<br>    if not redis_ok:<br>        health_status[&quot;status&quot;] = &quot;unhealthy&quot;<br>    # Falls back to DB-only path when Redis is degraded</pre><p>When Redis is down, every request hits PostgreSQL instead of cache. Latency goes from ~2ms to ~10ms, throughput drops, but no duplicate charges. The system degrades — it does not fail.</p><p><strong>Trade-off:</strong> DB connection pool becomes the bottleneck when Redis is down. Degraded performance beats incorrect behavior.</p><h3>The acid test: 10 concurrent requests, exactly 1 transaction</h3><pre>def test_concurrent_identical_requests(concurrent_server):<br>    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:<br>        futures = [executor.submit(make_request) for _ in range(10)]<br>        responses = [f.result() for f in futures]<br>    db = SessionLocal()<br>    count = db.execute(<br>        text(&quot;SELECT COUNT(*) FROM payment_transactions WHERE idempotency_key = :key&quot;),<br>        {&quot;key&quot;: idempotency_key}<br>    ).scalar()<br>    assert count == 1, f&quot;Expected 1 transaction, got {count}&quot;</pre><p>Request Cache Lock Result A (fastest) Miss Acquired <strong>200</strong> — payment processed B–J Miss Rejected <strong>409</strong> B–J (retry) <strong>Hit</strong> — <strong>200</strong> (cached, ~2ms)</p><p>Request A wins the lock, calls the provider, creates a transaction, caches the response, releases the lock. Everyone else either gets 409 immediately or, on retry, hits the cache and gets A’s response. Same transaction ID. Same amount. Zero additional charges.</p><h3>Known gap</h3><p>If a worker crashes after creating a PROCESSING record but before completing, the lock expires after 30 seconds — but the database record stays PROCESSING forever. Any future request for that key returns 409 until manual cleanup.</p><p>The fix is a background job marking stale PROCESSING records as FAILED after a timeout. Not built yet. That&#39;s the honest limitation.</p><p><em>Full project on GitHub: </em><a href="https://github.com/Zyrexam/payment-idempotency-proxy"><em>github.com/Zyrexam/payment-idempotency-proxy</em></a><em> — runs in Docker, includes Prometheus metrics, a Grafana dashboard, and ~30 tests. Stack: FastAPI, redis.asyncio, SQLAlchemy 2.0, PostgreSQL, Prometheus, Grafana.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d21af5a718a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>