<?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 Jack Klimov on Medium]]></title>
        <description><![CDATA[Stories by Jack Klimov on Medium]]></description>
        <link>https://medium.com/@jaklimoff?source=rss-1302a4037ccf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vXsDb-V5jh2RZIYAeNxtFQ.png</url>
            <title>Stories by Jack Klimov on Medium</title>
            <link>https://medium.com/@jaklimoff?source=rss-1302a4037ccf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:21:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaklimoff/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[A2A Is for Strangers: When to Use A2A and When It’s Overhead]]></title>
            <link>https://medium.com/@jaklimoff/a2a-is-for-strangers-when-to-use-a2a-and-when-its-overhead-0fd9fa4f9982?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd9fa4f9982</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 00:00:30 GMT</pubDate>
            <atom:updated>2026-10-26T14:41:14.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlBpyLX7HVFqul0ugI262g.png" /></figure><p>A2A turns every agent you expose into a network service: a card and an endpoint, and for long, interactive work, a task store. That’s the right shape when the agent on the other side belongs to someone else (another department, a vendor, a platform), and a strange one when the agent is your own. That’s my answer to when to use A2A, and this post is the evidence: the same agent handoff built four ways in Docker, the one detailed production report I could find, and my own attempt to run a personal fleet on it.</p><p>Eon, the company behind that production report, put it in one line: “You can’t import a stranger’s agent. You can only call it.” A2A is a protocol for calling strangers. Your own agents are not strangers.</p><h3>What Does A2A Make You Run?</h3><p>The basics are in my <a href="https://jack.direct/blog/wild-west-of-ai-protocols/">MCP vs A2A post</a>. The short version: an A2A agent publishes an Agent Card at /.well-known/agent-card.json with its skills, endpoints and auth schemes. You send it a message. It answers with a task that has an ID and a state: submitted, working, input required, auth required, completed, failed, canceled or rejected. You poll it, stream it over SSE, or hand it a webhook. A quick call can skip all that: the server may answer with a plain message and no task, and push notifications are an optional capability.</p><p>The spec is short. For a long, interactive task like the one I tested below, what you own is not:</p><ul><li><strong>A task store.</strong> Tasks outlive the HTTP call. The Python SDK’s default handler keeps live streams in memory; for more than one replica its own code warns you to “route subscription requests to the replica holding the task.”</li><li><strong>Webhook configs that persist, if you offer push.</strong> The spec: the push configuration “MUST persist until task completion or explicit deletion.” The agent must attempt each delivery at least once and may retry, so a delivery can arrive twice or not at all: make the handler idempotent, and guard the URLs against SSRF.</li><li><strong>Auth.</strong> The card declares the schemes (API key, HTTP auth such as Bearer, OAuth2, OIDC, mTLS) and the server must authenticate every request, but getting the credential is out of band: A2A says to rely on “established web security practices.” On the “auth required” state, the spec says it “does not define the scope, representation, validity, or revocation semantics of the authorization decision.”</li><li><strong>Two versions.</strong> 1.0 shipped in March 2026 with 16 breaking changes. Seven months later Gemini Enterprise, SAP Joule, IBM watsonx Orchestrate and CrewAI’s default all still speak 0.3. The Python SDK carries about 8,000 lines just to translate 0.3.</li><li><strong>Trust.</strong> The other agent’s card is text your model reads. Trustwave showed a rogue card description can win every task from an LLM host. Card signing is optional, and right now two SDKs produce different bytes for the same card, so signatures don’t verify across them.</li></ul><p>None of this is exotic. It’s the normal cost of putting a service on the network. The question is whether your agent needs to be a service on the network at all.</p><h3>When to Use A2A</h3><p>When the agent on the other side is a stranger. In practice that means two cases.</p><p><strong>Another department or another company.</strong> The test isn’t the company badge. It’s whether the other side has its own owner, its own release cycle, its own credentials and its own on-call. You can’t read their code and you can’t ship it for them. A server with a published contract, its own HTTP endpoint and webhooks is exactly what you want between those two worlds. This is the case Eon describes: about 20 of its specialist agents stay in one service, where a function call is enough, and 3 went behind A2A, each with a reason to sit across a boundary. One held production credentials and shipped on the backend’s release cycle. One changed with the data model. The third kind was built by tenants.</p><p>A separate owner doesn’t make A2A necessary on its own, though. It earns its place when a standard contract helps: several callers you don’t control, or a platform that requires it. For one caller you can talk to, a plain API is enough.</p><p><strong>A platform that plugs in outside agents through A2A.</strong> Gemini Enterprise, Microsoft Foundry, Copilot Studio, SAP Joule, ServiceNow and Atlassian Rovo all connect to outside agents over A2A. Copilot Studio only calls out: your agent is the A2A server. If your agent has to show up inside one of them, A2A is the entry ticket. Build it as one adapter at the edge, not as the way your own agents talk to each other. The protocol itself isn’t hard to implement. What’s hard is good introspection of your own fleet, and A2A doesn’t give you that.</p><p>Google’s own ADK docs draw the line from both sides. They suggest A2A for a separate, standalone service, an agent from another team or organization, one in a different language or framework, or when you need a formal contract between agents. And they say not to use A2A for internal code organization, for latency-critical internal calls, for agents that share memory, or for simple helpers. On shared memory: “A2A’s network overhead and serialization/deserialization would be counterproductive.”</p><h3>What Does A2A Cost Next to MCP, NATS and a Function Call?</h3><p>To see the cost instead of arguing about it, I built one scenario four ways, all in Docker. An orchestrator hands a task to a worker. The worker does four steps, sends progress after each, asks one question after step 2 (“Short or long summary?”), waits for the answer, and returns a result. Stub agents, no model calls: I wanted the coordination layer alone. An agent (Claude) wrote the code, and it all runs from one script in throwaway containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSRHo7UQxmFMoSG4cjnQrg.png" /><figcaption>The same handoff built four ways. 200 sequential runs per variant, one Docker network, no TLS, auth or concurrency.</figcaption></figure><p>Versions: a2a-sdk 1.2.3, mcp 2.3.0, nats-py 2.16.0 with NATS server 2.14, Python 3.12. 200 sequential runs per variant after 10 warmup runs, on an M1 Max, all containers on one Docker network: no TLS, no auth, no concurrency. Task latency is one full task, measured by the orchestrator from handoff to result, with clients and connections reused between runs. The question round trip is measured by the worker, from sending the question to holding the answer. So this ranks these four implementations, not the protocols in every setup. And NATS moves the weight out of your process into a broker you run, persist and upgrade: by bytes deployed it&#39;s A2A 51.5 MB, MCP 38.9 MB, NATS 27.3 MB.</p><p>Two things stand out, and they pull in opposite directions.</p><p>First, latency is usually not the argument. A few milliseconds per task disappear next to a model that thinks for seconds. A paper that measured A2A against a lighter protocol found the same: the gap is “almost entirely from connection setup,” tens of milliseconds; connection caching narrows it, and it reaches near parity once inference dominates. It matters for short, frequent or many-hop calls, and Google lists latency-critical internal calls as a reason to skip A2A. For agent-sized work, the cost is code, packages, and the things you now operate.</p><p>Second, the last row. I gave a 40-line client, Python standard library only, nothing but the A2A worker’s base URL. It read the card, found the endpoint, streamed the task, saw TASK_STATE_INPUT_REQUIRED, answered on the same taskId, and got the result. First try. No shared code, no shared types, just the spec. NATS can&#39;t do that: the subjects are a private convention only my orchestrator understands. MCP comes closest: a generic client can discover the server&#39;s tools, capabilities and instructions, and call them. But there&#39;s no A2A-style card with skills and task states, and MCP&#39;s design assumes you trust the server.</p><p>That’s the whole trade in one table. In this test A2A was the heaviest option, and the only one with a card a stranger’s client could read and drive.</p><h3>What Happened When I Killed the Worker?</h3><p>I ran two crash tests per variant with docker kill: once in the middle of the work, once while the question was waiting for an answer. Then I restarted the same worker.</p><p>These are the setups I tested, not an either/or. A2A is the contract a caller sees; a broker is one way to make work survive a crash. One system can have both: an A2A door at the edge with JetStream behind it. Each setup is minimal: A2A with its default in-memory store, A2A with its sqlite store swapped in, and NATS with a durable JetStream pull consumer, a 5-second ack wait, worker heartbeats, and a 5-line check in the worker that finds an answer already in the stream after a redelivery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yvteeTwII1IZgVyXMAdSA.png" /><figcaption>Crash in the middle of the work, three setups.</figcaption></figure><p>With A2A’s default in-memory store, the streaming client sees the connection drop at once, which is good, but no task is marked failed, and after the restart the task is gone: TaskNotFoundError after the restart. Swap in a durable sqlite store and a crash mid-work leaves a task that reads TASK_STATE_WORKING forever. Nothing in the SDK marks it failed; you write the reaper. A task paused on its question did survive with sqlite, because it wasn&#39;t running anything. Durability had a cost here: the SDK&#39;s sqlite store (DatabaseTaskStore over aiosqlite, default settings) took the median from 6.4 ms to 95.6 ms while writing every event. That&#39;s this store in this setup, not the price of durability in general.</p><p>NATS did the opposite. The orchestrator never heard about the crash; it saw about 6 seconds of silence. But the broker redelivered the task to the restarted worker, and it completed with zero recovery code in the orchestrator. The price is that the worker must be safe to run twice.</p><p>MCP’s new stateless version has a trick of its own: a paused call carries its state with the client, so with a shared key any server process can resume it. But in the 2026‑07‑28 version it can’t pause a running tool at all; ctx.elicit() fails with &quot;no back-channel for server-initiated requests,&quot; and the tool has to checkpoint and return.</p><p>The lesson isn’t that one protocol wins. Recovery is something you design, and A2A doesn’t design it for you.</p><h3>What Happened When I Ran My Own Fleet on A2A?</h3><p>I built an internal system for my own agents on A2A, with AG-UI for the interface. One agent, Picasso, made images on request: other agents could ask it for a picture and it drew one in my brand style. Another was a snob, a hater whose job was to come in and tear an article to shreds, so I could see where it was weak.</p><p>The roles were good. But A2A made the whole setup heavy, especially for a personal mini fleet. And it didn’t solve the problems that actually mattered: coordinating the work through a board, and giving the agents their tools.</p><p>A2A answers “how does agent A call agent B.” In my own fleet that was never the hard question.</p><h3>What to Use Instead of A2A for Your Own Agents</h3><p>What I took from that attempt: sometimes plain harnesses are simpler, and when coordination gets serious, a well-organized message bus does it better. As a ladder:</p><ol><li><strong>Subagents inside one harness.</strong> Claude Code subagents, OpenAI Agents SDK handoffs, LangGraph’s subagents pattern. A subagent is a function call with a long runtime. No card, no task store, no auth, because nothing crosses a boundary. OpenAI’s maintainers said in August they “do not plan to add an SDK-owned A2A abstraction” to their Agents SDK.</li><li><strong>Two harnesses that talk to each other.</strong> Sometimes it’s simpler to start two agents in a terminal multiplexer like <a href="https://herdr.dev/">herdr</a> and ask them to talk. No protocol at all.</li><li><strong>A message bus plus a board, when coordination gets serious.</strong> HTTP servers and webhooks suit agents open to outside systems. Inside, a message bus is much better. My own setup is a private system where agents, the loop that drives them, and I all meet on one NATS bus. Task state lives on a board, not in the messages, so there is never a second copy of it. When an agent needs an answer, it asks and ends its turn; the answer starts a new turn in the same session.</li></ol><p>Map that bus against A2A and several of A2A’s ideas are already there under other names. A role card instead of an Agent Card. A thread ID instead of a contextId. &quot;Ask and end the turn&quot; instead of INPUT_REQUIRED. What&#39;s missing is exactly the stranger part: discovery across organizations, cross-company identity, an HTTP door for agents that can&#39;t join the bus.</p><p>And if you need that door later, you don’t rebuild the house. You put one A2A adapter at the edge, the same way Cotal and Solace Agent Mesh carry A2A’s message shapes over a broker instead of making every agent an HTTP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYR-c61_d9uafS7rpoXGVA.png" /><figcaption>When to use A2A, and what to use when you don’t.</figcaption></figure><h3>Is the Protocol the Hard Part?</h3><p>No. Implementing A2A isn’t hard. The hard part is seeing what your fleet is doing: which agent holds which task, why one stalled, what it asked and who answered. A protocol for agents to talk doesn’t give you that.</p><p>The research points the same way. CooperBench, from Stanford and SAP, gave two coding agents separate but potentially conflicting features in the same codebase, across more than 600 tasks. Working together, they did much worse than one agent doing both features: GPT-5 solved 48% alone and 28% as a pair. Letting them message each other cut naive merge conflicts but didn’t raise success. The failures were jammed channels, broken commitments and wrong beliefs about what the partner was doing.</p><p>More talking is not coordination. That’s why my own setup coordinates through a board, not a chat channel.</p><p>To me, A2A looks like another enterprise solution: it adds more constraints than it removes problems, unless you’re calling a stranger’s agent. The numbers back the caution. Last month a2a-sdk was downloaded 11.4 million times from PyPI; mcp was downloaded 235 million times. Pydantic AI moved its A2A support out of its core in May, into a separate bridge. Downloads measure ecosystem pull, not which architecture is right, but the gap is wide. And Eon, the one team with a detailed production write-up, said both that &quot;adopting A2A added failure modes rather than removing them&quot; and &quot;We&#39;d choose A2A again.&quot; Both are true. It&#39;s the right tool at a real boundary, and the wrong default for a tightly coupled fleet of your own.</p><h3>When to Use A2A: The Short Version</h3><ul><li>Use A2A where your agent meets a stranger and a standard contract pays off: several callers you don’t control, or a platform like Gemini Enterprise or Copilot Studio that requires it. One caller you can talk to? A plain API is enough.</li><li>Inside your own fleet, don’t make every agent a network service. Use subagents first, two harnesses talking when that’s enough, and a message bus plus a board when coordination gets serious.</li><li>If you ship A2A, check which version your callers speak (many still need 0.3), and if your tasks run long, plan a durable task store, a reaper for tasks stuck in “working”, and your own credential flow.</li><li>Spend the effort you saved on introspection: one place where you can see every task, every question and every answer.</li></ul><p>If you’re deciding where the agent boundaries sit in your own system, that’s the kind of work I do: <a href="https://jack.direct/about/">get in touch</a>.</p><p><em>Originally published at </em><a href="https://jack.direct/blog/when-to-use-a2a/"><em>https://jack.direct</em></a><em> on October 26, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd9fa4f9982" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Not to Use RAG: Log Your Misses First]]></title>
            <link>https://medium.com/@jaklimoff/when-not-to-use-rag-log-your-misses-first-c8282f88493c?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8282f88493c</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 00:00:04 GMT</pubDate>
            <atom:updated>2026-10-19T15:09:02.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQjp7wqFusQijQYxbJppug.png" /></figure><p>The default for agent memory gets decided before anyone measures anything: chunk it, embed it, buy a vector database. I kept a boring full-text index instead. After a week I went back through every search my agent had run, to see what the skipped step would have bought me.</p><p>57 searches. 11 came back empty. Two were the kind of miss embeddings fix. The other 9 were plumbing. That’s my short answer to when not to use RAG: when you don’t know yet what your search misses.</p><p>This post is about embedding-based RAG: an embedding model, a vector store, the top-k chunks pasted into the prompt. My setup retrieves too. The question isn’t whether to retrieve. It’s whether to add the embedding model before you have a log.</p><h3>A Memory Small Enough to Read</h3><p>The memory is a private side project: long-term memory for my Claude Code sessions. Markdown notes are the source of truth, with relations and grouping between them, plus clean transcripts of past sessions. It started as a small graph of markdown files, and RAG was obviously overkill for that.</p><p>So the search side is boring on purpose. One SQLite file with an FTS5 index and the trigram tokenizer, so substring search works the same for Russian and English. An MCP server with search_notes and search_transcripts, ranked by BM25. And a UserPromptSubmit hook that pushes relevant notes into the context on every prompt, because a model doesn&#39;t search for what it doesn&#39;t know exists.</p><p>Here’s the whole memory as a graph, labels blurred because some notes are personal: one box per project, global facts and the always-loaded rules in the middle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kjGMuSxo-eSSrho0.png" /></figure><p>Today that’s 214 live notes and about 11,000 transcript messages. I set one rule about vectors: “Embeddings only once FTS misses are collected.” Then I didn’t build the part that collects them, not until this post. So a week in, I read the raw session logs instead.</p><h3>What Were the 11 Empty Searches?</h3><p>The best one came on the day I wired in Jev, the yes/no model this post gets to in a minute. My agent searched memory for “JEV” and got nothing in both stores. The conversation where Jev came up hadn’t been indexed yet. The memory couldn’t remember what it had learned that day.</p><p>Day one had its own moment: unable to open database file. The rest sorted like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCkc6Ft4HuuG9s5LATQ4Lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*sLRZIHv9S0BsY4aaFOw9Mg.png" /><figcaption>Where the 11 empty searches broke. Embeddings only change the last step.</figcaption></figure><p>Nine plumbing misses, and not one of them cares what you embed with. A stale index stays stale with vectors on top. The biggest class, “not indexed yet”, is a scheduling problem: the index rebuilds when a session ends and once a night. The export and the index both cope with a session that’s still running; they just don’t get called until some session ends. A hook after every turn fixes it in under a second, and I wired one in while writing this.</p><p>The meaning misses are more fun. An agent searched for “contrarian” and got nothing, because the conversation it wanted had happened in Russian. It retried with a Russian word stem for “objection” and found it. That’s a textbook case for embeddings. The second was a Russian medical abbreviation, where the note says it in English.</p><p>Then there was “ментор”, Russian for “mentor”. I first filed it as a correct empty, since nothing indexed mentioned mentors. On a second look, the session that ran the search had been about mentors since its first message that morning. The search came from a subagent, which doesn’t see its parent’s context, and the parent wasn’t indexed because it was still running. So it wasn’t a meaning miss at all, just a fifth “not indexed yet”. The agent’s English retry did “find” something, though: a September message about reusing the implementor session. Trigram search matches substrings, and “mentor” lives inside “implementor”.</p><p>That last one is the failure my count can’t see. I counted empty results. A search that returns the wrong thing looks like a success in the log, and my own server makes that the likelier failure: it runs an AND query first, then falls back to OR on any word, so a multi-word search almost never comes back empty. So this count can’t tell you what embeddings would save me overall. It only tells you that most of the empty searches had nothing to do with meaning.</p><h3>A Reranker With Nobody in Front of It</h3><p>The more interesting part is recall, the notes the hook pushes in without being asked. It runs on Jev, TypeSafe’s System One: a model that answers yes/no questions with calibrated probabilities. On every prompt, the hook asks it one question per note the session may see: would showing this note help answer this message? Notes at 0.6 or above get shown, at most 3.</p><p>“May see” is scope, not relevance: global notes, the current project’s notes, and related projects’, minus the handful of rules every session loads and the notes this session was already shown. There’s no search step in front of Jev. In a normal pipeline a retriever picks the top 50 and a reranker reads them. My pool is 33 notes on a median prompt, so the retriever has nothing to do and the reranker reads everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Akx0FE-vKYZIpjIJt3JPCg.png" /><figcaption>A usual RAG pipeline next to the recall hook: no retriever in front, and silence is an allowed answer.</figcaption></figure><p>From 14 to 19 October that was 432 prompts and about 15,000 yes/no judgments. The Jev call took a median of 357 ms and about 6,300 input tokens, and it never once fell back to the keyword scorer behind it. Good, because that scorer found 5 of the 13 eval notes to Jev’s 8, and since facts left the always-loaded index, this hook is how most of them reach a session. One vendor’s uptime is now load-bearing for my memory. The hook showed a note on 71 of those prompts, 16%. The rest got silence.</p><p>It isn’t free, and it isn’t private. Those five days took about 2.9 million input tokens, which at the list price of $0.042 per million is about 12 cents. The privacy cost is bigger: every prompt, scrubbed only of the secret formats I know to look for, plus each eligible note’s name, description and first 300 characters, goes to an API. The privacy case against a hosted embedding API isn’t “nobody sees your notes”. It’s a second vendor and a second copy.</p><p>Why not skip the judge and paste the notes into the prompt? Anthropic’s advice for a knowledge base under about 200,000 tokens is exactly that. The fair version isn’t all 214 notes; it’s the pool a session may see: 37 to 80 notes today, depending on the project, roughly 5,000 to 20,000 tokens, loaded once and cached. That’s cheap enough to work, and my reason for not doing it doesn’t survive a second look. In this blog’s project, 35 of the pool’s 52 notes are global, and 23 of those are personal facts about me. I’d just taken them out of the always-loaded index, which went from about 5,700 characters to under 2,000, so they’d stop riding along in every coding session. But the judge still read all 23 on every prompt of every project, and sent them to a second vendor. The pool was scoped by what’s true everywhere, not by what a session should see. That was a scoping gap, not a privacy design, and the fix was a flag per project.</p><p>So writing this post changed the system. Personal notes now stay out of every project I haven’t marked as personal. The index updates after every turn, which kills the biggest miss class. And the search log this whole post is about finally exists. Next, from my design doc: a nightly pass that marks which injected notes actually got used, and embeddings for Russian-English search over transcripts, still behind the rule that the misses get collected first. Now they will be.</p><h3>Would Embeddings Have Beaten the Judge?</h3><p>The fair objection: Jev was only ever compared with a keyword scorer. Maybe embeddings do better. So I ran bge-m3, a multilingual embedding model, locally on the same 20 hand-picked eval prompts. Same pool per prompt, same note text Jev sees. 13 prompts want a note; 7 should show nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HE3KmgkGJ5yYdA45Ka3eGQ.png" /></figure><p>“Found” counts prompts where at least one wanted note was shown (two prompts want two). “Wrong notes” is the total of unwanted notes shown across all 20 prompts, at most 3 per prompt.</p><p>As a ranker, bge-m3 is good. It put a wanted note in its top 3 on 9 of 13 prompts, one better than Jev. Plain top-3 can’t say no, though: it shows three notes on every prompt, including the 7 that wanted nothing.</p><p>The standard fix is a cosine cutoff, and here it’s a knife-edge. When a note was wanted, the best score ran from 0.45 to 0.69. When nothing was wanted, it ran from 0.43 to 0.57. The ranges overlap, so every cutoff trades one failure for the other. At 0.50 it matches Jev’s 8 finds with two and a half times the wrong notes. At 0.57 it finally stays quiet and finds 5. Move the cutoff by 0.02 and the wrong notes swing by 5 to 8. On these 20 cases, Jev’s cutoff gave the better balance of finds and junk. I won’t claim more than that: a vendor’s calibrated probability is calibrated on their data, not mine, and both cutoffs here were tuned on the same cases.</p><p>Embeddings win on speed and privacy: 39 ms per prompt on a laptop GPU against Jev’s ~350 ms over the network, and nothing leaves the machine. The price is a 2.27 GB model that has to stay loaded.</p><p>Two more results worth knowing. bge-m3 is multilingual, and it showed no edge on Russian here: of the 4 Russian prompts that wanted a note, each found 1. The likelier culprit is my notes: they’re mostly written in English, so neither judge has much to match a Russian prompt against. And of Jev’s 5 misses, bge-m3 caught 2 in its top 3, both English.</p><p>Caveats, loudly. 20 cases, one user. Every cutoff here, Jev’s 0.6 included, was picked on the same 20 cases it was scored on; nothing was held out. I tested only bge-m3’s dense mode, with no reranker. Nothing yet measures whether an injected note actually got used. And two of Jev’s 6 wrong notes were personal notes shown on prompts that didn’t ask for them. It’s a smoke test, not a benchmark.</p><h3>Why Don’t Claude Code and Cursor Use RAG?</h3><p>The coding agents walked the same road at a scale that makes my week look like a rounding error. Claude Code started on a vector index and dropped it for <a href="https://jack.direct/blog/claude-code-unpacked-what-512k-lines-of-leaked-source-tells-you-about-agentic-ai/">agentic grep</a>; Boris Cherny calls the decision “mostly vibes”, plus some internal benchmarks.</p><p>Cursor is the one worth reading closely. In November 2025 it measured a 12.5% accuracy gain from semantic search and published it. By mid-2026 its docs said it “does not store embeddings of your codebase for search”, because the models had got good enough at grep that the semantic path was “no longer helping in a meaningful way”. The gain was real, and the index still went.</p><p>Their mechanism isn’t mine: their model drives the search, my hook pushes notes. The lesson is the same, though: keep the index while you can measure what it buys, and drop it when you can’t.</p><h3>When Should You Use RAG?</h3><p>Embeddings win in real cases, and both of my meaning misses look like candidates. Use them when:</p><ul><li><strong>The corpus is too big to judge or to fit in the prompt.</strong> Thousands of documents: a support knowledge base with 10,000 articles, a company’s Slack and Confluence. A judge that reads every note stops scaling long before that.</li><li><strong>Users search in another language than the docs.</strong> A trigram index can’t match a Russian word to its English twin at all. On BGE-M3’s own benchmark (MKQA, Recall@100), Russian cross-lingual recall is 76.2 for dense embeddings against 33.2 for BM25. My 20 cases didn’t show that gap, but they’re 20 cases.</li><li><strong>People don’t know the words.</strong> “Can’t sleep” against “insomnia” in support tickets. Prose written weeks apart in different words is vocabulary mismatch, and lexical search loses there.</li><li><strong>Every query must take milliseconds and no LLM tokens.</strong> Product search, autocomplete, high query volume.</li></ul><p>Even then, go hybrid. In Anthropic’s Contextual Retrieval tests, the top-20 retrieval failure rate was 5.7% with embeddings alone and 1.9% with contextual embeddings, contextual BM25 and a reranker. Keep the lexical side for exact identifiers like “TS-999”, which an embedding model can miss.</p><h3>What to Build Before You Use RAG</h3><p>Building agent memory, internal search, or a “chat with our docs” feature? Start lexical, and build the log I didn’t have:</p><ol><li>SQLite FTS5 with BM25. One file, no model, rebuilds in seconds.</li><li>Log every search with how many results it returned, and mark the retry that follows an empty one.</li><li>Keep 20 hand-picked eval cases, including prompts that should return nothing.</li><li>If the corpus is small, put an LLM judge over the candidates.</li><li>Add embeddings only for the miss class you’ve measured.</li></ol><p>Steps 1 and 2 fit in about 25 lines:</p><pre>import json<br>import sqlite3<br>import time<br><br>db = sqlite3.connect(&quot;:memory:&quot;)  # a demo; for real use, a file and db.commit()<br>db.execute(&quot;CREATE VIRTUAL TABLE notes USING fts5(name, body, tokenize=&#39;trigram&#39;)&quot;)<br>db.execute(&quot;INSERT INTO notes VALUES (?, ?)&quot;, (&quot;deploy&quot;, &quot;Release with release/deploy.sh, never on Friday&quot;))<br>last_miss = None  # (time, query) of the last search that found nothing<br><br><br>def search(query: str, limit: int = 5) -&gt; list[str]:<br>    global last_miss<br>    # Trigram matches substrings of 3+ characters; shorter words can&#39;t match at all.<br>    terms = [t for t in query.split() if len(t) &gt;= 3]<br>    match = &quot; AND &quot;.join(&#39;&quot;&#39; + t.replace(&#39;&quot;&#39;, &#39;&quot;&quot;&#39;) + &#39;&quot;&#39; for t in terms)<br>    sql = &quot;SELECT name FROM notes WHERE notes MATCH ? ORDER BY bm25(notes) LIMIT ?&quot;<br>    rows = db.execute(sql, (match, limit)).fetchall() if terms else []<br>    entry = {&quot;ts&quot;: time.time(), &quot;query&quot;: query, &quot;returned&quot;: len(rows)}<br>    # A crude guess: any search within 2 minutes of an empty one counts as its retry.<br>    if last_miss and entry[&quot;ts&quot;] - last_miss[0] &lt; 120:<br>        entry[&quot;retry_of&quot;] = last_miss[1]<br>    with open(&quot;searches.jsonl&quot;, &quot;a&quot;) as log:<br>        log.write(json.dumps(entry, ensure_ascii=False) + &quot;\n&quot;)<br>    last_miss = None if rows else (entry[&quot;ts&quot;], query)<br>    return [name for (name,) in rows]<br><br><br>print(search(&quot;Friday deploy&quot;))  # [&#39;deploy&#39;]<br>print(search(&quot;push to prod&quot;))   # [], logged with returned: 0<br>print(search(&quot;deploy.sh&quot;))      # [&#39;deploy&#39;], logged as a retry of &quot;push to prod&quot;<br>print(search(&#39;deploy&quot;&#39;))        # [], and a stray quote doesn&#39;t crash it</pre><p>Once a week, read searches.jsonl and tag the misses: not indexed yet, wrong store, exact identifier, other language, paraphrase. Embeddings can only help with the last two. Then read a few searches that did return something, because &quot;mentor&quot; finding &quot;implementor&quot; never shows up as a miss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DHJbm1PhRagF2JnEpkMQw.png" /><figcaption>What the tags tell you to build.</figcaption></figure><p>My trigger for this memory: about one meaning miss a day, or Jev judging 80 to 100 notes per prompt. Both numbers are picked, not measured. I can count meaning misses only now that the search log exists, and pool size barely moves latency: 352 ms at 20 to 29 notes, 394 ms at 50 to 59. What grows is tokens, about 200 per note, and how much of my memory a second vendor reads on every prompt. Some prompts already reach 70 notes. When the pool needs a cap, embeddings come in, next to the full-text index rather than instead of it.</p><p>So: log your misses for two weeks before you buy a vector database. If the tags say “other language” and “paraphrase” more than once a day, go buy it, and keep the full-text index next to it for the identifiers. If they say “not indexed yet” and “wrong store”, you have a cron problem, and no embedding model has ever fixed a cron problem.</p><p>The recall hook here is a plain Claude Code hook. If you haven’t wired one yet, start with <a href="https://jack.direct/blog/claude-code-hooks-complete-guide/">the hooks guide</a>.</p><p><em>Originally published at </em><a href="https://jack.direct/blog/when-not-to-use-rag-log-your-misses-first/"><em>https://jack.direct</em></a><em> on October 19, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8282f88493c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Warning My Agent Gave That I Never Saw]]></title>
            <link>https://medium.com/@jaklimoff/the-warning-my-agent-gave-that-i-never-saw-fd9457192172?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd9457192172</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 00:00:43 GMT</pubDate>
            <atom:updated>2026-10-17T22:26:35.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hawkbUCVv86ZpNo28S427g.png" /></figure><p>My agent warned me, and I never saw the warning. Everyone has the same Claude Code, so your edge is how you bend it to the way you work, and a Claude Code mod makes the bending cheap: about 250 lines, written by the agent itself, that fixed the exact thing that burned me.</p><p>I was building a feature and sent agents to implement it. Then I found out it was built poorly. The warning came as a question, right there in the reply. More text came after it, I read the more text, and I never answered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b7YfJ9wJHaBl8uVM.gif" /></figure><h3>Why do agent questions get lost in Claude Code?</h3><p>Because they live in prose. A question or a warning is one sentence in the middle of a long reply, and the reply keeps going: a summary, a diff, tool output. Your eye goes to the end. The sentence that needed you scrolls away.</p><p>I’m not the only one. At least seven issues in the Claude Code repo, open and closed, describe the same thing. One puts it better than I can:</p><blockquote><em>Questions get silently dropped: Claude then proceeds on an assumption (wasted work) or waits for an answer nobody noticed was needed (stalled work).</em></blockquote><p>The first one is what got me.</p><h3>Why a tool, and not a CLAUDE.md rule?</h3><p>The obvious fixes are rules. “Always put your questions at the end.” “Summarize open questions in bold.” They work until the reply gets long, which is exactly when you need them.</p><p>I wanted structure instead of discipline. It is easier to give the agent a tool and track its questions in a structured way. Each question becomes a record with an id, not a sentence I have to find. And I can answer only some of them, in plain prompt text, and leave the rest open.</p><p>Claude Code already has a structured option, AskUserQuestion. It takes one to four multiple-choice questions and stops the turn until you answer. That fits when the agent can&#39;t go on without you. It doesn&#39;t fit the questions an agent collects while it keeps working: free text, not blocking, answered when you get to them.</p><p>Anthropic also shipped “You should know”, a built-in feature (off by default) where a side agent posts a note above the prompt when it spots something you might have missed. It flags things. It doesn’t keep a list you can answer.</p><h3>What is a Claude Code mod?</h3><p>A mod is a plugin whose code runs inside Claude Code instead of as a shell command. It can watch an event, change it, or take it over, and it can draw: a pane beside the transcript or a band above the prompt. Mods shipped in v2.1.287 on 2026-10-01 and are on by default. No build step: Claude Code loads .ts and .tsx files directly.</p><p>A plugin becomes a mod when its hooks/hooks.json names a module:</p><pre>{ &quot;modules&quot;: [&quot;./open-questions.tsx&quot;] }</pre><p>The open-questions mod hooks four events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TeyREm201t8h051BgYMlg.png" /></figure><p>The tool’s description is the whole contract with the model:</p><pre>await $.tool.register({<br>  name: &#39;questions&#39;,<br>  isDeferred: false,<br>  description:<br>    &#39;Track the questions you ask the user. Each time your reply asks the user a question that needs an answer, &#39; +<br>    &#39;call this tool with `ask` (one short line for each question). When the user answers a question, or it no &#39; +<br>    &#39;longer applies, call it with `answered` (the ids). Do not track rhetorical questions or offers. &#39; +<br>    &#39;Returns the open questions.&#39;,<br>  inputSchema: {<br>    type: &#39;object&#39;,<br>    properties: {<br>      ask: { type: &#39;array&#39;, items: { type: &#39;string&#39; } },<br>      answered: { type: &#39;array&#39;, items: { type: &#39;number&#39; } },<br>    },<br>  },<br>})</pre><p>isDeferred: false makes Claude see the full description every turn instead of only the tool&#39;s name. It needs v2.1.293 or later.</p><h3>Claude Code wrote it. The tuning is the work.</h3><p>I didn’t write the mod. Claude Code did.</p><p>The hard part came after: tuning it every time I hit an edge case or a spot where it didn’t work. The git log shows it: nine commits over about 28 hours, and the main file grew from 118 lines to 246.</p><ul><li><strong>Answers became drafts.</strong> You type an answer and it waits; one button sends them all in one message.</li><li><strong>The first unanswered question opens by itself</strong>, so ctrl+x tab lands in its field and you just type.</li><li><strong>Stale questions.</strong> Answer something in your own words and the box kept it. Now every prompt carries the open list, and Claude closes the ones the message answered or made moot.</li><li><strong>The single-question case.</strong> One commit hid the box when only one question was open. Two commits and twenty-five minutes later, it came back. One question is still easy to lose: the talk moves on to something else, and the question is still open. With the box, neither I nor the agent forgets it.</li><li><strong>Two questions got the same id.</strong> Parallel tool calls handed out the same number. Now the ids are reserved in one update.</li></ul><p>Each of these showed up while I used it, not while I planned it.</p><h3>What changed: zero missed questions</h3><p>Since then I haven’t missed a single question from the agent, and nothing important slipped. In the session where this post was planned and drafted, the agent filed 62 questions through the tool, and none was asked only in the text.</p><p>That number rests on Claude calling the tool, because nothing in the code checks that a question got filed. In my sessions it has. While I recorded the demo above, Opus 5.5 filed its questions and Sonnet 5.5, with the same prompt and setup, wrote them as plain text and never called the tool. If your agent skips it, the box can’t help: try another model, or sharpen the description.</p><h3>Who it is not for</h3><ul><li>You run one agent at a time and read every reply to the end. A lost question is rare for you, and the box is noise.</li><li>Headless runs (claude -p, CI). Nobody is there to answer, and mods don&#39;t draw there anyway.</li><li>An agent that already over-asks. A tracker rewards asking, which is why the description says “Do not track rhetorical questions or offers.”</li></ul><p>It also doesn’t draw in the VS Code extension, and /clear, /resume and /branch start an empty list.</p><h3>How to build your own Claude Code mod</h3><p>People look for ready solutions: someone’s config, someone’s plugin pack. Right now the best thing you can do is learn to customize the tool yourself.</p><ol><li>Pick one annoyance that keeps coming back in your own setup. Mine was a warning I scrolled past.</li><li>Ask Claude to write the mod. Claude Code has a built-in plugin-authoring skill for exactly this, and it reloads the mod as you go.</li><li>Use it for a day and write down every time it gets in your way. Each note is the next commit.</li></ol><p>Or start from mine. The code, the tests and the install line are in <a href="https://github.com/jaklimoff/claude-open-questions">jaklimoff/claude-open-questions</a>:</p><pre>/plugin marketplace add jaklimoff/claude-open-questions<br>/plugin install open-questions@open-questions</pre><p>Tested with Claude Code v2.1.302. Mods can still change between releases, so treat it as something you own and tune, not something you install and forget.</p><p><em>Originally published at </em><a href="https://jack.direct/blog/the-warning-my-agent-gave-that-i-never-saw"><em>https://jack.direct</em></a><em> on October 17, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd9457192172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Threading, Semaphores, and Barriers]]></title>
            <link>https://medium.com/@jaklimoff/python-threading-semaphores-and-barriers-e7ff65aa79ad?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7ff65aa79ad</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 19:02:29 GMT</pubDate>
            <atom:updated>2024-07-12T19:02:29.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*O9LRSPga0dz8YouW.png" /></figure><h3>1. Introduction to Python Threading</h3><p>Picture a bustling kitchen during the dinner rush. Chefs, sous chefs, and kitchen staff all work simultaneously, each focused on their tasks but coordinating their efforts to create a seamless dining experience. This orchestrated chaos is not unlike Python threading, where multiple tasks run concurrently within a single program.</p><p>Threading in Python allows developers to write programs that can juggle multiple operations at once, much like the kitchen analogy I gave before. It’s a way to make your code more efficient, responsive, and capable of handling complex tasks without chaos and anxiety.</p><p>Let’s break it down with a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GYlqi9YuZMgHu3fJ.png" /></figure><h4>Check the output here</h4><pre>Starting to prepare Pasta<br>Starting to prepare Salad<br>Pasta is ready!<br>Salad is ready!<br>All dishes are prepared!</pre><p>In this snippet, we’ve created two threads that simulate chefs preparing different dishes. The magic happens when both threads start — they run simultaneously, mimicking two chefs working side by side in the kitchen.</p><p>Threading shines in scenarios where you’re dealing with I/O-bound tasks, like reading files or making network requests. It allows your program to continue working while waiting for these potentially slow operations to complete.</p><p>However, it’s not all sunshine and rainbows. 😦 Threading comes with its own set of challenges:</p><ol><li><strong>Race conditions</strong>: When threads access shared resources, unexpected results can occur if not managed properly.</li><li><strong>Deadlocks</strong>: Threads can get stuck waiting for each other, like two polite people insisting the other go first through a doorway. (BTW I have wrote an article about <a href="https://jack.direct/understanding-deadlocks-in-python-with-examples/">deadlock in python here</a>)</li><li><strong>Complexity</strong>: Debugging threaded applications can be tricky, as the order of execution isn’t always predictable.</li></ol><p>As we venture deeper into the world of Python threading, we’ll explore tools like semaphores and barriers that help manage these challenges. These synchronization primitives act like the head chef in our kitchen, ensuring that all the moving parts work together harmoniously.</p><p>Threading is a powerful tool in a developer’s toolkit, but it requires careful handling. In the following sections, I will explain semaphores and barriers below, so you never question what they are for and how to use them 😎. So get ready — we’re about to cook up some serious code, hehe..!</p><h3>2. Understanding Semaphores in Python</h3><p>Imagine a busy coffee shop with a limited number of espresso machines. Baristas need to coordinate their use to avoid chaos and ensure smooth operation. This scenario perfectly illustrates the concept of semaphores in Python threading.</p><p>Semaphores are like the shift manager at our imaginary coffee shop, controlling access to shared resources. They act as counters, allowing a set number of threads to access a resource simultaneously. When a thread wants to use a resource, it asks the semaphore for permission. If the semaphore’s count is greater than zero, the thread is allowed access, and the count decreases. When the thread is done, it notifies the semaphore, and the count increases.</p><p>Let’s break this down with a Python example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kwpuy23QEy91xCfw.png" /></figure><h4>Check the output here</h4><pre>Alice is using the espresso machine<br>Bob is using the espresso machine<br>Bob is done making coffee<br>Alice is done making coffee<br>David is using the espresso machine<br>Charlie is using the espresso machine<br>David is done making coffee<br>Charlie is done making coffee<br>All coffee orders are complete!</pre><p>In this example, we’ve created a semaphore that allows two threads (baristas) to use the espresso machines simultaneously. The with statement ensures that the semaphore is properly released even if an exception occurs, to avoid deadlock.</p><p>Semaphores come in two flavors:</p><ol><li><strong>Counting Semaphores</strong>: These allow a specified number of threads to access a resource, like in our coffee shop example.</li><li><strong>Binary Semaphores</strong>: These are essentially locks, allowing only one thread at a time.</li></ol><p>Semaphores are particularly useful when you need to:</p><ul><li>Limit access to a fixed number of resources</li><li>Control the order of thread execution</li><li>Implement producer-consumer scenarios</li></ul><p>However, they’re not without potential pitfalls:</p><ul><li>Deadlocks can occur if not used carefully</li><li>Overuse can lead to reduced parallelism</li><li>They don’t protect against all types of race conditions</li></ul><p>As you work with semaphores, you’ll find they’re a powerful tool for managing concurrency. They allow you to create more complex and efficient threaded applications, much like how a well-organized coffee shop can serve more customers with limited resources.</p><h3>3. Barriers: Synchronizing Multiple Threads</h3><p>Imagine a group of friends planning to meet at a movie theater. They’ve agreed that no one enters until everyone arrives. This scenario perfectly captures the essence of barriers in Python threading.</p><p>Barriers act as synchronization points in multithreaded programs, ensuring that a group of threads reach a certain point before any of them can proceed. It’s like a virtual meeting spot where threads wait for their peers before moving forward together.</p><p>Let’s break this down with a Python example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e3HiPRQYPVFn9Gc8.png" /></figure><h4>Check the output here</h4><pre>Alice has arrived at the theater<br>Bob has arrived at the theaterCharlie has arrived at the theater<br>David has arrived at the theater<br>David is entering the theaterAlice is entering the theater<br>Bob is entering the theater<br>Charlie is entering the theater<br>Everyone is inside. The movie is starting!</pre><p>In this example, we’ve created a barrier for four friends. Each thread (representing a friend) calls barrier.wait() when they arrive. The barrier blocks until all four friends have called wait(). Once the last friend arrives, the barrier releases all threads simultaneously.</p><p>Barriers are particularly useful when:</p><ul><li>You need to synchronize multiple threads at specific points in your program</li><li>You’re dealing with phased operations where all threads must complete one phase before moving to the next</li><li>You want to ensure that data is fully prepared before processing begins</li></ul><p>Some key points to remember about barriers:</p><ol><li><strong>They’re reusable:</strong> After all threads are released, the barrier resets and can be used again.</li><li><strong>They can have a timeout</strong>: You can set a maximum wait time to prevent indefinite blocking.</li><li><strong>They can execute an action when the barrier is full</strong>: This is useful for setup or cleanup operations.</li></ol><p>Here’s an extended example showcasing these features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2qsCYaTIJ2hOafLw.png" /></figure><h4>Check the output hereCheck the output here</h4><pre>Worker-2 finished phase 0<br>Worker-0 finished phase 0<br>Worker-1 finished phase 0<br>All threads reached the barrier. Starting next phase.<br>Worker-2 finished phase 1<br>Worker-1 finished phase 1<br>Worker-0 finished phase 1<br>All threads reached the barrier. Starting next phase.<br>Worker-0 finished phase 2<br>Worker-2 finished phase 2<br>Worker-1 finished phase 2<br>All threads reached the barrier. Starting next phase.<br>All work completed</pre><p>This example demonstrates a multi-phase operation where threads synchronize at the end of each phase. The barrier executes a function when full and has a timeout to prevent indefinite waiting.</p><p>While barriers are powerful, they’re not without potential issues:</p><ul><li>They can lead to deadlocks if not all threads reach the barrier</li><li>Overuse can reduce parallelism and overall performance</li><li>They may mask logical errors in your program flow</li></ul><p>Barriers provide a good way to coordinate multiple threads so you can create more structured and predictable multithreaded applications. As you see explore more threading scenarios, you’ll find barriers to be an important key tool to fight the chaos 🥷</p><h3>4. Implementing Semaphores and Barriers</h3><p>Now that you got the concepts of semaphores and barriers, let’s roll up our sleeves and see how we can implement these synchronization tools in real-world scenarios. Think of this as moving from theory to practice — like transitioning from reading a cookbook to actually cooking in the kitchen.</p><p>Let’s start with a practical example that combines both semaphores and barriers. Imagine we’re simulating a multi-stage rocket launch, where different systems need to be checked and synchronized before liftoff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKpcVi0L26Ky43p6.png" /></figure><h4>Check the output here</h4><pre>Starting system check: Propulsion<br>Starting system check: Navigation<br>Starting system check: Life Support<br>System check complete: Life Support<br>Life Support waiting for other systems<br>Starting system check: Communication<br>System check complete: Navigation<br>Navigation waiting for other systems<br>System check complete: Propulsion<br>Propulsion waiting for other systems<br>System check complete: Communication<br>Communication waiting for other systems<br>Communication ready for launch!Life Support ready for launch!<br>Propulsion ready for launch!<br>Navigation ready for launch!<br>All systems go! Initiating launch sequence.</pre><p>In this rocket launch simulation:</p><ol><li>We use a semaphore to limit the number of concurrent system checks to 3. This might represent a limitation in the number of technicians or diagnostic tools available.</li><li>The barrier ensures that all four main systems complete their checks before the launch sequence can begin.</li><li>Each system check takes a random amount of time, simulating real-world variability.</li></ol><p>This example showcases how semaphores and barriers can work together to create a more complex and realistic synchronization scenario.</p><p>💡 When implementing your next rocket launcher project with semaphores and barriers, keep these tips in mind:</p><ol><li>Always release semaphores: Use context managers (with statements) or try/finally blocks to ensure semaphores are released.</li><li>Handle potential exceptions: Barrier’s wait() method can raise a BrokenBarrierError if the barrier is reset or times out.</li><li>Consider using timeouts: Both semaphores and barriers support timeouts to prevent indefinite waiting.</li><li>Be mindful of the thread count: Ensure the number of threads matches the barrier count to avoid deadlocks.</li></ol><h3>6. Performance Considerations</h3><p>When working with Python threading, semaphores, and barriers, performance is like a delicate balancing act. It’s not just about making your code run faster, but about making it run smarter. Let’s dive into some key performance considerations that can help you fine-tune your multithreaded applications.</p><h3>The Global Interpreter Lock (GIL)</h3><p>First things first, let’s address the elephant in the room: Python’s Global Interpreter Lock (GIL). The GIL is like a traffic controller that only allows one thread to execute Python bytecode at a time. This means that for CPU-bound tasks, threading might not give you the performance boost you’re expecting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U5ZzWi2ATzWHjOzq.png" /></figure><h4>Check the output here</h4><pre>Single thread time: 1.9691720008850098<br>Multi-thread time: 1.9881441593170166</pre><p>Running this code, you might be surprised to find that the multi-threaded version doesn’t perform significantly better, and might even be slower due to the overhead of thread management.</p><h3>I/O Bound is Where Threading Shines</h3><p>For I/O-bound tasks, however, threading can significantly improve performance. While one thread is waiting for I/O, others can execute, making efficient use of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xMg1AVnAVc1d7ZDh.png" /></figure><h4>Check the output here</h4><pre>Sequential time: 23.489413738250732<br>Parallel time: 2.472808837890625</pre><p>This example demonstrates how threading can dramatically speed up I/O-bound operations.</p><h3>7. The end</h3><p>So now you know the most important tools to tame python threading and improve performance of your backend server or whatever you use it for 🥸. If you read till this point, I just want to thank you and wish you the best day ever ;) . Stay cool, stay positive and pay attention to semaphores on the roads too!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7ff65aa79ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Theorem for Developers: What It Is and How It Affects Distributed Systems]]></title>
            <link>https://medium.com/@jaklimoff/cap-theorem-for-developers-what-it-is-and-how-it-affects-distributed-systems-73e862ef2c6f?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e862ef2c6f</guid>
            <category><![CDATA[cap]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 12:33:26 GMT</pubDate>
            <atom:updated>2024-07-03T12:33:26.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to CAP Theorem</h3><p>Picture yourself as an architect, tasked with designing a sprawling digital metropolis. Your city isn’t built from concrete and steel, but from interconnected servers and data centers. As you sketch out your plans, you realize you’re facing a fundamental challenge that has puzzled computer scientists for decades: how to create a system that’s both rock-solid reliable and lightning-fast responsive, even when parts of it go dark.</p><p>This is where the CAP theorem steps onto the stage, like a wise mentor offering guidance in your digital urban planning. Coined by Eric Brewer in 2000, the CAP theorem is a concept that’s as central to distributed systems as gravity is to physics. It’s a principle that whispers in the ear of every developer working on large-scale applications, reminding them of the inherent trade-offs they’ll face.</p><p>At its heart, the CAP theorem tells us a bittersweet truth: in a distributed system, you can’t have your cake and eat it too. It states that when it comes to Consistency, Availability, and Partition tolerance, you can only choose two out of these three desirable properties at any given time.</p><p>Think of these properties as the three pillars of an ideal distributed system:</p><ul><li><strong>Consistency ©</strong>: Every read receives the most recent write or an error</li><li><strong>Availability (A)</strong>: Every request receives a response, without guarantee that it contains the most recent version of the information</li><li><strong>Partition Tolerance (P)</strong>: The system continues to operate despite arbitrary partitioning due to network failures</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzDJZee7tS64GSETdffl3Q.png" /></figure><p>As we peel back the layers of the CAP theorem, we’ll see how these pillars interact, conflict, and compromise. We’ll explore why you might choose consistency over availability in some cases, or vice versa. And we’ll grapple with the reality that in a world where networks can fail, partition tolerance isn’t so much a choice as a necessity.</p><p>The CAP theorem isn’t just a theoretical concept — it has real-world implications that shape the architecture of systems we interact with daily, from social media platforms to e-commerce giants. As we journey through this article, we’ll see how the CAP theorem influences design decisions, affects user experiences, and continues to evolve in the face of new technologies and paradigms.</p><p>So, let’s discuss all the ideas behind the CAP theorem. It’s a journey that will hopefully spark your creativity, give you new knowledge and ultimately make you better architect… and better person. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Md9yqWJmF9jZ_s7sj-2EkA.png" /></figure><h3>The Three Components: Consistency, Availability, and Partition Tolerance</h3><p>Let’s take a closer look at the three pillars of the CAP theorem, imagining them as the vital organs of our distributed system’s body. Each component plays a crucial role, and understanding their nature helps us to see the inherent trade-offs we face with them.</p><h3>Consistency: The System’s Memory</h3><p>Picture consistency as the system’s ability to tell a coherent and truthful story. When we talk about consistency in distributed systems, we’re referring to all nodes seeing the same data at the same time. It’s like having a group of friends who always have the exact same information, no matter who you ask or when you ask them.</p><p>In practice, this means that after an update is made to the system, all subsequent read operations will return that updated value. If you can’t guarantee this, you might need to return an error rather than potentially outdated information.</p><p>Consider a banking app. When you make a transfer, consistency ensures that your new balance is reflected accurately across all parts of the system. Without it, you might see different balances depending on which server you connect to — a recipe for confusion and potential financial chaos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skcWpOg00vGL58u6DnGFYA.png" /></figure><h3>Availability: The System’s Responsiveness</h3><p>Availability is like the system’s heartbeat — it keeps things alive and responsive. An available system promises to respond to every request, be it a read or a write operation. It doesn’t guarantee that the response will contain the most up-to-date information, but it does assure that you’ll get a response, not an error.</p><p>Imagine a social media platform during a major event. Millions of users are posting updates simultaneously. An available system will ensure that users can continue to post and view content, even if some of the information isn’t immediately consistent across the entire network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*50N-KVRmwfZuHLbt.jpg" /></figure><h3>Partition Tolerance: The System’s Resilience</h3><p>Partition tolerance is the system’s immune system, allowing it to continue functioning even when communication breaks down between its parts. In a distributed system, network failures are not just possible; they’re inevitable. Partition tolerance is the ability to handle these failures gracefully.</p><p>Think of a global e-commerce platform with data centers across continents. If the transatlantic cable is damaged, partition tolerance ensures that European customers can still shop, even if they can’t see real-time updates from American inventory for a while.</p><h3>The Interplay and Trade-offs</h3><p>Here’s where things get interesting — and challenging. In a perfect world, we’d have all three of these properties working in harmony. But the CAP theorem tells us this isn’t possible in a distributed system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VAkftz2Sw25KYDuKb_Lsaw.png" /></figure><ul><li>If we prioritize consistency and availability, we sacrifice partition tolerance. This might work in a small, reliable network, but it’s not feasible for most real-world distributed systems.</li><li>If we choose consistency and partition tolerance, we might have to reduce availability. During a network partition, the system might refuse requests to prevent inconsistent data.</li><li>If we opt for availability and partition tolerance, we accept that our data might not always be consistent. This is often the choice for systems that prioritize user experience over absolute data accuracy.</li></ul><p>As developers, we’re constantly balancing these properties based on our system’s needs. A financial system might lean heavily towards consistency, while a content delivery network might prioritize availability.</p><p>Understanding these components and their interactions is crucial for designing robust systems, especially distributed systems. It’s not about finding a one-size-fits-all solution, but about making informed decisions based on your specific requirements and constraints.</p><p>In the next section, we’ll explore how these trade-offs play out in real-world scenarios, giving you an understanding of how the CAP theorem shapes the systems we build and use every day.</p><h3>Understanding Trade-offs in Distributed Systems</h3><p>Imagine you’re a chef in a bustling restaurant kitchen. You’ve got three prized ingredients — let’s call them C, A, and P — but your recipe can only accommodate two of them. This is the essence of the trade-offs we face in distributed systems due to the CAP theorem.</p><h3>The Balancing Act</h3><p>In the world of distributed systems, making choices between consistency, availability, and partition tolerance is like walking a tightrope. Each decision tilts the balance, affecting how our system behaves under different conditions.</p><p>Imagine a real-time multiplayer game. Players expect immediate feedback (availability) and a fair, synchronized game state (consistency). But what happens when network issues arise (partition)? Do we pause the game to maintain consistency, potentially frustrating players? Or do we allow the game to continue with potential inconsistencies, risking unfair gameplay?</p><p>These aren’t just theoretical questions — they’re the bread and butter of system design decisions that developers grapple with daily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*YqwTklOpsF3JPHpM.jpg" /></figure><h3>The CP Approach: When Accuracy is King</h3><p>Systems that prioritize consistency and partition tolerance (CP) are like precision instruments. They ensure that all nodes have the same data, even if it means some requests might be denied during network partitions.</p><p>Database systems often lean towards this approach. For instance, when you’re checking your bank balance, you’d rather see an error message than an incorrect amount. In these cases, the system might choose to become temporarily unavailable to avoid serving stale or inconsistent data.</p><h3>The AP Strategy: Keeping the Show Running</h3><p>On the other hand, systems that favor availability and partition tolerance (AP) are like the show-must-go-on performers of the tech world. They ensure the system keeps responding, even if the data might not be the latest across all nodes.</p><p>Think of a social media feed. If there’s a network partition, you might not see the very latest posts from your friends, but the app continues to function, showing you older content rather than an error message.</p><h3>The CA Compromise: Ideal but Impractical</h3><p>While it’s theoretically possible to have a system that’s consistent and available (CA), it comes at the cost of partition tolerance. In the real world of distributed systems, where network failures are a fact of life, this is often an impractical choice.</p><p>A small-scale, single-data-center application might achieve CA, but as soon as you scale across multiple data centers or regions, partition tolerance becomes a necessity.</p><h3>The Art of Choosing</h3><p>Selecting the right trade-off isn’t a one-time decision — it’s an ongoing process that evolves with your system’s needs and constraints. Here are some factors to consider:</p><ol><li><strong>Data Criticality</strong>: How crucial is data accuracy for your application? Financial systems might lean towards CP, while social networks might prefer AP.</li><li><strong>User Experience</strong>: Will users tolerate occasional unavailability, or is constant access more important than perfect consistency?</li><li><strong>Scale and Distribution</strong>: The more widely distributed your system, the more important partition tolerance becomes.</li><li><strong>Regulatory Requirements</strong>: Some industries have strict data consistency requirements that may influence your choices.</li><li><strong>Failure Modes</strong>: How does your system behave when things go wrong? Understanding this can help you make more informed trade-offs.</li></ol><h3>Beyond Binary Choices</h3><p>It’s worth noting that in practice, these trade-offs aren’t always binary. Modern distributed systems often employ nuanced strategies that blend aspects of different approaches:</p><ul><li><strong>Eventual Consistency</strong>: This model, used by systems like Amazon’s Dynamo, accepts temporary inconsistencies but ensures that data will converge to a consistent state over time.</li><li><strong>Tunable Consistency</strong>: Some systems allow developers to specify consistency levels for different operations, providing flexibility in how trade-offs are managed.</li><li><strong>Multi-Model Databases</strong>: These systems can switch between different consistency models based on the specific needs of different parts of the application.</li></ul><p>Understanding these trade-offs is crucial for building resilient, efficient distributed systems. It’s not about finding a perfect solution, but about making informed decisions that align with your system’s goals and constraints.</p><h3>CAP Theorem in Practice: Real-world Examples</h3><p>Theory is good, but without practice it costs nothing. So how about real-world applications? The CAP theorem isn’t just an academic concept — it’s a guiding principle that shapes the architecture of systems we interact with every day. Here are some examples that bring the CAP theorem to life:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*CHXks7zuNwzm3tQv.jpg" /></figure><h3>Amazon’s Dynamo: Embracing AP for Shopping Carts</h3><p>Let’s take an Amazon during online sale. Millions of shoppers, all clicking ‘Add to Cart’ simultaneously. Amazon’s Dynamo database, which powers their shopping cart system, is a prime example of an AP (Availability and Partition Tolerance) system.</p><p>Dynamo prioritizes availability, ensuring that customers can always add items to their carts, even if there’s a network partition. It uses eventual consistency, meaning that while your cart might not immediately reflect changes across all nodes, it will eventually catch up.</p><p>This approach makes sense for Amazon. A temporarily inconsistent shopping cart is far less problematic than a cart that’s unavailable during a busy shopping period. The trade-off? You might occasionally see an item reappear in your cart after removing it, but the system never stops working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9B-q3_nTeIKvrgHg.png" /></figure><h3>Google’s Spanner: Pushing the Boundaries with CP</h3><p>Now, let’s zoom into Google’s data centers, where Spanner, their globally distributed database, resides. Spanner is a great case because it aims to provide strong consistency © while maintaining partition tolerance (P).</p><p>How does it manage this seemingly impossible feat? Through the clever use of atomic clocks and GPS timing, Spanner can synchronize transactions across the globe with remarkable precision. This allows it to maintain consistency even during network partitions.</p><p>The trade-off here is potential unavailability during severe network issues. However, for many of Google’s services where data accuracy is crucial, this is an acceptable compromise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hchbvk0nuHsaUzxs.png" /></figure><h3>Cassandra: Tunable Consistency for Flexibility</h3><p>Apache Cassandra, used by companies like Netflix and Instagram, offers a more flexible approach. It allows developers to tune consistency levels on a per-operation basis.</p><p>Imagine you’re building a video streaming service. For user profile updates, you might choose strong consistency to ensure accurate information. But for viewing history, where occasional inconsistency is less critical, you might opt for eventual consistency to improve performance.</p><p>This flexibility showcases how modern systems are evolving beyond strict CAP categorizations, allowing developers to make nuanced trade-offs based on specific use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nKwh9iPDOm7M7n1A_TL-Lw.png" /></figure><h3>Bitcoin: Eventual Consistency in Decentralized Systems</h3><p>The Bitcoin network presents an interesting application of CAP principles in a decentralized context. It prioritizes partition tolerance and availability over immediate consistency.</p><p>When you make a Bitcoin transaction, it’s not immediately ‘final’. Instead, it becomes more certain over time as more blocks are added to the blockchain. This eventual consistency model allows the network to continue operating even when parts of it are disconnected or under attack.</p><p>The trade-off? You need to wait for several confirmations before considering a large transaction truly complete, which can take up to an hour.</p><h3>Lessons from the Real World</h3><p>These examples illustrate several key points:</p><ol><li><strong>Context Matters</strong>: The right CAP trade-off depends heavily on the specific needs of your application.</li><li><strong>Hybrid Approaches</strong>: Many real-world systems don’t strictly adhere to CP or AP but use a mix of strategies.</li><li><strong>Evolving Solutions</strong>: As technology advances, we’re finding new ways to mitigate CAP theorem limitations.</li><li><strong>User Experience Focus</strong>: Ultimately, CAP trade-offs are about providing the best possible user experience within technical constraints.</li></ol><p>By examining these real-world applications, we can see how the CAP theorem isnt just a theoretical construct but a practical guide for building resilient, scalable distributed systems. As you design your own systems, these examples can serve as inspiration for creative solutions to the ever-present CAP dilemma.</p><h3>Strategies for Designing CAP-aware Systems</h3><p>Designing systems with the CAP theorem in mind is like crafting a finely balanced machine. It requires careful consideration, creative problem-solving, and a deep understanding of your specific needs. Let’s explore some strategies that can help you navigate the complex landscape of distributed systems design.</p><h3>1. Know Your Requirements Inside Out</h3><p>Before diving into the technical details, take a step back and really understand what your system needs to achieve:</p><ul><li>What’s the primary function of your application?</li><li>How critical is data consistency to your users?</li><li>Can your system tolerate brief periods of unavailability?</li><li>What’s your expected scale and geographical distribution?</li></ul><p>Answering these questions will give you a solid foundation for making informed CAP trade-offs.</p><h3>2. Embrace Eventual Consistency Where Appropriate</h3><p>Eventual consistency can be a powerful tool in your CAP-aware design arsenal. It allows you to prioritize availability and partition tolerance while still providing a form of consistency over time.</p><p>Consider implementing eventually consistent models for non-critical data. For example, in a social media application, likes and comments could be eventually consistent, allowing for high availability even during network partitions.</p><h3>3. Implement Multi-Version Concurrency Control (MVCC)</h3><p>MVCC is like having a time machine for your data. It allows multiple versions of data to coexist, which can be particularly useful in distributed systems.</p><p>By implementing MVCC, you can improve availability and concurrency while maintaining a level of consistency. Users can always read a consistent (though potentially slightly outdated) version of the data, while writes can proceed without blocking reads.</p><h3>4. Use Conflict Resolution Techniques</h3><p>In distributed systems, conflicts are inevitable. Preparing for them is key to maintaining system integrity.</p><p>Implement conflict resolution strategies such as:</p><ul><li>Last-write-wins (LWW)</li><li>Custom merge functions</li><li>Vector clocks to track causality</li></ul><p>These techniques can help your system automatically resolve conflicts that arise due to network partitions or concurrent updates.</p><h3>5. Leverage Caching Strategically</h3><p>Caching is like having a cheat sheet for your data. It can significantly improve availability and performance, but it needs to be managed carefully to avoid consistency issues.</p><p>Consider using:</p><ul><li>Read-through and write-through caching</li><li>Cache invalidation strategies</li><li>Time-to-live (TTL) settings</li></ul><p>Remember, caches introduce another layer of complexity in terms of consistency, so use them judiciously.</p><h3>6. Implement Circuit Breakers</h3><p>Circuit breakers are like safety valves for your system. They can prevent cascading failures in distributed systems by failing fast and providing fallback mechanisms.</p><p>By implementing circuit breakers, you can improve your system’s resilience to network partitions and maintain a level of availability even when parts of the system are struggling.</p><h3>7. Design for Failure</h3><p>In distributed systems, failure is not just possible — it’s inevitable. Design your system with this reality in mind:</p><ul><li>Implement retry mechanisms with exponential backoff</li><li>Use bulkheads to isolate failures</li><li>Design fallback mechanisms for critical operations</li></ul><p>By preparing for failure, you can create a system that gracefully handles the challenges posed by the CAP theorem.</p><h3>8. Consider CRDT (Conflict-Free Replicated Data Types)</h3><p>CRDTs are like magic building blocks for distributed systems. They are data structures that can be replicated across multiple computers in a network, where the replicas can be updated independently and concurrently without coordination between the replicas, and it is always mathematically possible to resolve inconsistencies that might result.</p><p>By using CRDTs, you can achieve strong eventual consistency without sacrificing availability or partition tolerance.</p><h3>9. Implement Sharding</h3><p>Sharding is like dividing a big problem into smaller, more manageable pieces. By partitioning your data across multiple nodes, you can improve scalability and reduce the impact of network partitions.</p><p>However, be aware that sharding introduces its own complexities, especially when it comes to maintaining consistency across shards.</p><h3>10. Monitor and Measure Religiously</h3><p>You can’t improve what you don’t measure. Implement comprehensive monitoring and alerting for your distributed system:</p><ul><li>Track consistency levels</li><li>Monitor network partitions</li><li>Measure response times and availability</li></ul><p>This data will be invaluable in understanding how your CAP trade-offs are playing out in the real world and where improvements can be made.</p><h3>11. Educate Your Team</h3><p>Finally, remember that designing CAP-aware systems is a team effort. Ensure that everyone involved in the design, development, and operation of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ymRoE63Phd3I-8vf.jpg" /></figure><h3>Limitations and Criticisms of CAP Theorem</h3><p>While the CAP theorem has been a cornerstone of distributed systems theory for over two decades, it’s not without its limitations and critics. As with any widely accepted principle, it’s crucial to understand not just its strengths, but also its weaknesses and the ongoing debates surrounding it. Let’s peel back the layers and examine some of the key criticisms and limitations of the CAP theorem.</p><h3>Oversimplification of Complex Systems</h3><p>One of the primary criticisms of the CAP theorem is that it presents a somewhat binary view of distributed systems, which can oversimplify the nuanced reality of modern architectures.</p><p>In practice, consistency and availability aren’t all-or-nothing properties. There’s a spectrum of consistency models ( strong, eventual, causal, etc.) and various degrees of availability. The CAP theorem doesn’t capture these nuances, potentially leading to overly simplistic design decisions.</p><p>For instance, a system might provide high availability for reads but lower availability for writes, or it might offer different consistency guarantees for different types of data. These subtleties are not readily apparent in the basic CAP model.</p><h3>Focus on Extreme Conditions</h3><p>The CAP theorem primarily addresses behavior during network partitions, which, while important, are relatively rare events in many systems. Critics argue that this focus on extreme conditions may lead designers to make suboptimal choices for the more common, non-partitioned state of the system.</p><p>It’s a bit like designing a car solely based on how it performs in a crash test, while neglecting its everyday driving characteristics. While crash safety is crucial, it shouldn’t be the only consideration in car design.</p><h3>Neglect of Other Important System Properties</h3><p>By focusing solely on consistency, availability, and partition tolerance, the CAP theorem might lead designers to overlook other critical system properties. Factors like latency, throughput, and data freshness can be equally important in many scenarios.</p><p>For example, a system might be consistent and available, but if it’s excruciatingly slow, it might as well be unavailable from a user’s perspective. The CAP theorem doesn’t address these performance aspects directly.</p><h3>The “2 out of 3” Misconception</h3><p>A common misinterpretation of the CAP theorem is the idea that a distributed system must always choose exactly two out of the three properties. In reality, the theorem only states that during a network partition, a system must choose between consistency and availability.</p><p>This misconception can lead to flawed system designs where designers believe they must entirely sacrifice one property, when in fact more nuanced trade-offs are possible.</p><h3>Evolution of Network Technologies</h3><p>As network technologies have evolved, some argue that the fundamental assumptions of the CAP theorem may need revisiting. Modern networks are often more reliable and have lower latency than when the theorem was first proposed.</p><p>While network partitions can still occur, their frequency and impact might be different in today’s landscape, potentially altering the calculus of CAP trade-offs.</p><h3>Lack of Consideration for Time and Scale</h3><p>The CAP theorem doesn’t explicitly account for the role of time in consistency models. In real-world systems, consistency often has a temporal aspect — data might become consistent after a certain period, even if it wasn’t immediately consistent.</p><p>Similarly, the theorem doesn’t directly address how trade-offs might change as a system scales. A small system might easily achieve all three properties, while a global, highly distributed system faces more significant challenges.</p><h3>Alternative Models and Refinements</h3><p>In response to these limitations, researchers and practitioners have proposed various refinements and alternative models:</p><ul><li>PACELC theorem: This extends CAP by considering system behavior both during partitions (PA/EL) and in the absence of partitions (PC/EC).</li><li>BASE (Basically Available, Soft state, Eventual consistency): This model provides an alternative to ACID for designing systems that prioritize availability.</li><li>The “CAP Twelve Years Later” paper by Eric Brewer himself, which revisits and clarifies some aspects of the original theorem.</li></ul><p>These alternatives and refinements aim to provide a more nuanced understanding of distributed systems trade-offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2Vy265WlKUFRSYyroJuoXg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e862ef2c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Stop Your Solidity Code from Guzzling Gas (and ETH!)]]></title>
            <link>https://coinsbench.com/how-to-stop-your-solidity-code-from-guzzling-gas-and-eth-779472b86381?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/779472b86381</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 10:27:12 GMT</pubDate>
            <atom:updated>2024-06-19T14:39:34.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76mcFGGS00tEsbTQXVD2RQ.jpeg" /></figure><p>So, you’ve dipped your toes into the wild world of blockchain and built your first smart contract with Solidity. Kudos! But before you pop the champagne and start minting NFTs like there’s no tomorrow, let’s talk about something crucial: <strong>gas optimization</strong>.</p><p>Think of gas as the fuel that powers your smart contract on the Ethereum network. Every line of code, every function call, every little calculation — it all needs gas to run. And just like in the real world, gas is not free. In fact, high gas fees can seriously eat into your profits (and your sanity :) ).</p><p>That’s where gas optimization comes in. It’s the art of writing smart contracts that are lean and efficient, so they consume less gas and save you precious ETH or whatever you pay for it.</p><h3><strong>Why Should You Care About Gas Optimization?</strong></h3><p>Imagine this: you’ve created an awesome decentralized app (DApp) that everyone’s raving about. But then, users start complaining about exorbitant transaction fees. Suddenly, your dream DApp becomes too expensive to use, and people lose interest. Ouch.</p><p>Optimizing your Solidity code for gas efficiency isn’t just about saving a few bucks… it’s about:</p><ul><li><strong>Accessibility:</strong> Lower gas fees make your dApp more accessible to a wider audience.</li><li><strong>Sustainability:</strong> Less gas consumption means a smaller carbon footprint for your project.</li><li><strong>User Experience:</strong> Nobody likes waiting for slow and expensive transactions. Gas optimization makes your dApp snappier and more enjoyable to use.</li></ul><h3><strong>Solidity Gas Optimization: Let’s Get Technical (But Not Too Technical)</strong></h3><p>Don’t worry, this isn’t going to be a dry and boring lecture on assembly code. We’ll stick to practical tips that even beginner Solidity developers can understand and implement.</p><p><strong>1. Data Structures: Choose Wisely, My Friend</strong></p><ul><li><strong>Arrays:</strong> Avoid unnecessary array resizing. Pre-allocate memory if you know the size beforehand. Remember, pushing data into a dynamically sized array is like trying to fit an elephant into a Mini Cooper — it’s gonna cost you!</li><li><strong>Mappings:</strong> Use mappings whenever possible. They’re like hash tables, offering super-fast lookups and saving you gas compared to iterating through arrays to find what you need.</li></ul><p><strong>2. Loops: The Bane of Gas-Guzzlers</strong></p><ul><li><strong>Minimize Loop Iterations:</strong> Keep those loops tight! The fewer times you have to loop, the less gas you’ll burn.</li><li><strong>Don’t Loop What You Can Calculate:</strong> If you can calculate a value directly instead of looping to find it, do it! Your gas tank will thank you.</li></ul><p><strong>3. Functions: Short, Sweet, and Gas-Efficient</strong></p><ul><li><strong>Internal vs. External:</strong> Use internal functions whenever possible. They&#39;re only callable from within the contract and are cheaper than external functions.</li><li><strong>Pure vs. View:</strong> If a function doesn’t modify the blockchain state, declare it as view (for reading data) or pure (for calculations only). These functions don&#39;t consume any gas when called externally.</li></ul><p><strong>4. Variables: Pack ’Em In Like Sardines</strong></p><ul><li><strong>Variable Packing:</strong> Solidity allows you to pack multiple variables into a single storage slot. This might sound like some black magic, but it’s a legit way to save gas on storage.</li><li><strong>Use Unsigned Integers:</strong> When you know a value will always be positive, use an uint instead of an int. Unsigned integers take up less space and are cheaper to work with.</li></ul><p><strong>5. Libraries: Don’t Reinvent the Wheel</strong></p><ul><li><strong>Leverage Existing Libraries:</strong> Chances are, someone has already solved a problem you’re facing. Use well-tested and optimized libraries to save time and gas.</li></ul><h3><strong>FAQs: Your Burning Gas Optimization Questions, Answered</strong></h3><p><strong>1. What is the most important thing to remember about gas optimization?</strong></p><p>Keep it simple! The more complex your code, the more gas it will consume. Write clean, concise, and readable code, and you’ll be on the right track.</p><p><strong>2. How can I estimate the gas cost of my Solidity code?</strong></p><p>Remix, the popular Solidity IDE, has a built-in gas estimator that can give you a rough idea of how much gas your code will consume. Hardhat has special plugin called <a href="https://www.npmjs.com/package/hardhat-gas-reporter">hardhat-gas-reporter</a> to measure gas consumption during tests. In foundry you can simply run tests with gas tracker flag like this: forge test --gas-report</p><p><strong>3. Are there any tools that can help me optimize my Solidity code?</strong></p><p>Yes! There are several tools available, such as:</p><ul><li><strong>Solhint:</strong> A linter that helps you identify potential code style and security issues, some of which can impact gas efficiency. [<a href="https://protofire.github.io/solhint/">site</a>]</li><li><strong>M</strong><a href="https://github.com/Consensys/mythril"><strong>ythril</strong></a><strong>:</strong> A security analysis tool that can also detect gas optimization opportunities. [<a href="https://github.com/ConsenSys/mythril">git</a>]</li></ul><p><strong>4. Is gas optimization a one-time thing?</strong></p><p>Not really. As your project evolves and you add new features, it’s crucial to revisit your code and optimize for gas efficiency regularly.</p><p><strong>5. I’m a beginner. Do I really need to worry about gas optimization right now?</strong></p><p>While it’s essential to understand the basics of gas optimization from the get-go, don’t get bogged down by it when you’re just starting. Focus on writing clean and functional code first, and then gradually incorporate optimization techniques as you gain more experience.</p><h3><strong>Gas Optimization: Your Key to a Smoother Blockchain Journey</strong></h3><p>Optimizing your Solidity code for gas efficiency is an ongoing process, but its a worthwhile investment that will pay dividends in the long run. By following these tips and staying up-to-date with the latest best practices, you can ensure that your DApps are accessible, sustainable, and a joy to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779472b86381" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/how-to-stop-your-solidity-code-from-guzzling-gas-and-eth-779472b86381">How to Stop Your Solidity Code from Guzzling Gas (and ETH!)</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Solidity Pragma: 6 Ways to Specify Compiler Versions]]></title>
            <link>https://coinsbench.com/mastering-solidity-pragma-6-ways-to-specify-compiler-versions-757bd9416cf0?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/757bd9416cf0</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 10:03:36 GMT</pubDate>
            <atom:updated>2024-06-14T21:20:29.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDxy8ikiqFJX1thOc5ZDbQ.png" /></figure><h3>Intro</h3><p>When you’re just starting out with Solidity smart contract development, the pragma line at the top of every .sol file might seem like just another piece of boilerplate. But don’t ignore the pragma — it’s an essential part of your Solidity code that tells the compiler which version to use.</p><p>Moreover solidity follows same syntax to define versions as used by `npm` package manager, which means that we have multiple ways to define version ranges.</p><h3>SemVer</h3><p>But before we begin, let’s briefly discuss Semantic Versioning (SemVer) to ensure we’re on the same page. The Solidity compiler adheres to the SemVer convention, meaning each version number carries specific compatibility details.</p><p>Here is how it looks like</p><pre>{MAJOR}.{MINOR}.{PATCH}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Tn6bAy1e-akOiaVduGIcg.png" /></figure><p><strong>MAJOR</strong> version when you make incompatible API changes<br><strong>MINOR</strong> version when you add functionality in a backward compatible manner<br><strong>PATCH</strong> version when you make backward compatible bug fixes</p><p>The current version of Solidity is 0.8.26, indicating that the major version is still 0. This typically means the project is considered to be in its initial development phase, despite being around for 10 years. As such, backward compatibility is not guaranteed for minor versions. Therefore, it’s crucial to specify the compiler version precisely in your contracts.</p><p>Now that we’ve got the basics of semantic versioning covered, let’s dive into the fun part — exploring the different ways to define your compiler of choice!</p><h3>6 ways to specify version</h3><h4>1. Exact Version</h4><p>The simplest way to set a pragma is by specifying the exact Solidity compiler version you want to use. Let’s say you just want to use version 0.8.25, then your pragma will look like this:</p><pre>pragma solidity 0.8.25;</pre><p>But in fact patch version can change really fast and it usually backward compatible, so if you want you fine with any patch version you can just leave it out and only define major and minor versions like this.</p><pre>pragma solidity 0.8;</pre><h4>2. Less Than / Greater Than Ranges</h4><p>You can also define a range of acceptable versions using the less than (&lt;) or greater than (&gt;) operators.</p><pre>pragma solidity &gt;=0.7.0;</pre><p>Or if you want to only include specific range of patch versions you can define it in this way.</p><pre>pragma solidity &gt;=0.7.1 &lt;0.7.5;</pre><h4>3. Hyphen Ranges</h4><p>There is another way to define ranges more concisely via hyphens like this:</p><pre>pragma solidity 0.8.0–0.8.20;</pre><p>This accepts versions from 0.8.0 to 0.8.20 inclusive.</p><h4>4. X-Ranges</h4><p>In some cases X-ranges can be more readable. The idea is that any of `X`, `x`, or `*` symbols may be used as a wildcard to substitute major, minor or patch versions. Here is the example:</p><pre>pragma solidity 0.8.x; // &gt;=0.8.0 &lt;0.9.0<br>pragma solidity 0.*; // &gt;=0.0.0 &lt;1.0.0</pre><h4>5. Tilde Ranges</h4><p>Tilde ranges is another way to define compiler version. They let you apply patch-level updates if you specify a minor version in the comparator.</p><p>In this example we accept all versions from 0.7.3 included up to 0.8.0 excluded. So basically it locks major and minor versions.</p><pre>pragma solidity ~0.7.3; // &gt;=0.7.3 &lt;0.8.0</pre><h4>6. Caret Ranges</h4><p>And the final way which is the most popular by far is caret ranges. They allow for updates that don’t change the first non-zero digit in the version number. This means they can accept more updates, providing greater flexibility.</p><pre>pragma solidity ^0.2.3; // &gt;=0.2.3 &lt;0.3.0</pre><h3>Conclusion</h3><p>Understanding the various ways to define version ranges in Solidity is crucial for smart contract development. It not only ensures compatibility with the intended compiler version but also provides flexibility to accommodate future updates and patch fixes. Whether you choose to specify exact versions or use ranges like hyphens, X-ranges, tilde, or caret notation, each method has its place depending on your project’s requirements and stability needs.</p><p>By mastering these versioning techniques, you can avoid common pitfalls and ensure that your contracts remain functional and secure as the Solidity language evolves. Remember, the pragma statement is more than just a line of code — it’s a key part of maintaining the integrity and reliability of your smart contracts. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757bd9416cf0" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/mastering-solidity-pragma-6-ways-to-specify-compiler-versions-757bd9416cf0">Mastering Solidity Pragma: 6 Ways to Specify Compiler Versions</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Pull over Push” pattern in solidity]]></title>
            <link>https://coinsbench.com/pull-over-push-pattern-in-solidity-fbf01d0613a7?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbf01d0613a7</guid>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Fri, 31 May 2024 16:01:04 GMT</pubDate>
            <atom:updated>2024-06-10T19:30:52.759Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>In the world of Ethereum smart contracts, transferring ETH can be tricky. The “Pull over Push” pattern is a method that shifts the responsibility of withdrawing funds from the contract to the user, ensuring smoother and safer transactions. This approach is crucial for avoiding common pitfalls when dealing with multiple recipients or complex contract logic.</p><h4>Why the Push Pattern Fails</h4><p>The traditional approach to sending funds — automatically pushing ether to users — seems straightforward but can lead to several issues.</p><p>Here’s a simplified example of push pattern, where we send transfer ETH directly to all receivers when push function is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnCW80MapHLFbArazcjo6g.png" /></figure><h4>Issues with the Push Pattern:</h4><ol><li><strong>Gas Limit Problems</strong>: Iterating over a large array of addresses can exceed the block gas limit, making the function fail.</li><li><strong>Expense for Contract Owner</strong>: The user who calls the withdraw function pays for all the gas, which can be really expensive.</li><li><strong>Potential for Failure</strong>: If even one transfer fails (e.g., due to a recipient contract throwing an error) the entire transaction will be reverted.</li></ol><h4>The Better Way — The Pull Pattern</h4><p>Instead of pushing funds to users, the pull pattern allows each user to withdraw their funds independently. This individualizes transactions, enhancing security and spreading out gas costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVjYvGRkEVcR7rCZp5QcfA.png" /></figure><h4>Benefits of the Pull Approach:</h4><ol><li><strong>Isolated Failures</strong>: Each withdrawal is a separate transaction. If one fails, others are unaffected.</li><li><strong>Fair Cost Distribution</strong>: Users only pay for their own withdrawals, which distributes the gas costs more fairly.</li><li><strong>Enhanced Efficiency</strong>: Avoids the inefficiency of looping through potentially large arrays, leading to lower gas usage</li></ol><h4>OpenZeppelin’s Implementation of the Pull Pattern</h4><p>If you want real world best practices, check how OpenZeppelin implements the Pull over Push pattern in its PullPayment.sol contract. This implementation leverages the Escrow contract to manage user funds securely, but the whole idea is pretty straightforward and should be clear for you already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1XCguSv6oMrzyJjZXYwWg.png" /></figure><h4>Conclusion</h4><p>The “Pull over Push” pattern offers a significant improvement in managing ether transfers within Ethereum smart contracts. By letting users withdraw their funds independently, this method enhances security and mitigates the risk of transaction failures. However, it is essential for developers to weigh the trade-offs and ensure that users are well-informed about the withdrawal process to maximize efficiency and user satisfaction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbf01d0613a7" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/pull-over-push-pattern-in-solidity-fbf01d0613a7">“Pull over Push” pattern in solidity</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deadlocks in Python with Examples]]></title>
            <link>https://medium.com/@jaklimoff/understanding-deadlocks-in-python-with-examples-20b5e00f1eb8?source=rss-1302a4037ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b5e00f1eb8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deadlock]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Jack Klimov]]></dc:creator>
            <pubDate>Sun, 19 May 2024 11:34:00 GMT</pubDate>
            <atom:updated>2024-05-19T11:36:51.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nCek-iGrWx5zoPQyFjF-Q.png" /></figure><p>Deadlocks are a common issue in concurrent programming, where multiple threads or processes are involved. They can cause your program to freeze indefinitely, making it unresponsive. This article will help you understand what deadlocks are, how they occur, and how to avoid them in Python.</p><h3>What is a Deadlock?</h3><p>A deadlock is a situation where two or more threads or processes are unable to proceed because each is waiting for the other to release a resource (Lock).</p><p>Imagine two bartenders working at a bar, each mixing a drink that requires the same two shakers. If both bartenders grab one shaker and wait for the other, they’ll never be able to finish their drinks, leading to a deadlock.</p><p>In programming, this happens when threads or processes hold onto resources and wait for others to release them, creating a cycle of dependency that halts progress.</p><h3>Common Causes of Deadlocks</h3><p>Deadlocks can occur in various ways, but here are some common scenarios:</p><ol><li><strong>Circular Wait</strong></li><li><strong>Self-Deadlock</strong></li><li><strong>Resource Starvation</strong></li></ol><p>Below I will show examples with code for better understanding.</p><h3>Circular Wait</h3><p>Like in example with two bartenders and shakers, circular wait can happen when thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Hopefully some example can make it even more clear.</p><p>In this code:</p><ol><li><strong>thread_a</strong> acquires <strong>lock1</strong> and then attempts to acquire <strong>lock2</strong>.</li><li><strong>thread_b</strong> acquires <strong>lock2</strong> and then attempts to acquire <strong>lock1</strong>.</li><li>Both threads get stuck waiting for the lock held by the other thread, resulting in a circular wait deadlock.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDUFy375unh1EqN0NJpxIQ.png" /></figure><p>As the result we only will see these logs before eternal hanging.</p><pre>Thread A acquired Lock 1<br>Thread B acquired Lock 2<br>Thread A trying to acquire Lock 2<br>Thread B trying to acquire Lock 1</pre><h3>Self-Deadlock Example</h3><p>Such situation is rather rare but still useful to mention. During self-deadlock thread tries to acquire the same lock twice and as the result hanging forever.</p><p>In this example:</p><ol><li>The thread acquires the lock the first time without any problems.</li><li>When it tries to acquire the same lock a second time, it gets stuck waiting for itself to release the lock, resulting in a deadlock.</li><li>The finally block and the program’s completion message will not execute because the thread is indefinitely blocked.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jewZ6qYQltASDZAO5mWjHA.png" /></figure><h3>Resource Starvation</h3><p>In this case a thread fails to release a resource (Lock), causing other threads to wait indefinitely. Usually is caused by loops or exceptions that are not handled properly.</p><p>In this code:</p><ol><li><strong>thread_with_exception</strong> acquires the <strong>lock</strong> and then raises an exception. The <strong>lock</strong> should ideally be released in the <strong>finally</strong> block, but if this is not done, the <strong>lock</strong> remains held.</li><li><strong>waiting_thread</strong> attempts to acquire the <strong>lock</strong>. It will be blocked indefinitely because <strong>thread_with_exception</strong> does not release the <strong>lock</strong> due to the unhandled exception.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pMMuDQMutHZrP_1rUanog.png" /></figure><p>As the result we only see following logs before freezing forever. :(</p><pre>Thread with Exception acquired the lock.<br>Exception caught: An unexpected error occurred!<br>Waiting Thread trying to acquire the lock...</pre><h3>How to Avoid Deadlocks</h3><p>Here are some best practices to avoid deadlocks:</p><ol><li><strong>Use Context Managers</strong>: Use with statement to manage locks. In this case locks will be released properly, even if an error occurs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWcfH1o4NIW58IR4_qjbVQ.png" /></figure><p>2. <strong>Consistent Lock Ordering</strong>: Make sure that you always acquire locks in the same order. This prevents circular wait conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UludPNWLxdeDyPgZ4dVl1Q.png" /></figure><p>3. <strong>Timeouts</strong>: Use timeout parameter when acquiring locks to avoid waiting indefinitely. Such simple trick can save from many unpredictable deadlocks in codebase with complicated logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9jNExhYsiURa6tSVKY5rg.png" /></figure><p>4. <strong>Avoid Nested Locks</strong>: Try to minimise the use of nested locks. If you can, design your program so that it doesn’t need to hold multiple locks simultaneously. Debugging code with lots of locks can be incredibly challenging and frustrating.</p><p>5. <strong>Keep Lock Scope Small</strong>: Hold locks for the shortest time possible. Perform non-critical operations outside the critical section to shorten the duration locks are held.</p><p>6. <strong>Deadlock Detection and Recovery</strong>: Implement deadlock detection mechanisms to monitor and recover from deadlocked states. This can be complex but useful for critical applications.</p><p>7. <strong>Concurrency Libraries</strong>: Use higher-level concurrency libraries like concurrent.futures which abstract away much of the complexity of threading and locking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H02yanwbqgsiGaJC2aP0bQ.png" /></figure><h3>Conclusion</h3><p>Deadlocks can be tricky to debug and resolve, but understanding their causes and following best practices can help you avoid them. I hope now you have a better understanding of deadlocks and will avoid them in your code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b5e00f1eb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>