
isolate-tx
io.github.tathagata1010/isolate-tx
Transactions for AI agents: stop concurrent agents from overwriting each other's shared state.
Documentation
Isolate
Transactions for AI agents
When several agents share data, one agent's decision can silently overwrite another's.
Isolate stops that, in any language, with one docker run.
Quickstart · Why · Use cases · Compare · How it works · Production · Docs
Get it: PyPI · npm · MCP Registry · Docker image · Release jars · Maven Central
💥 The bug every multi-agent system has
https://github.com/user-attachments/assets/11e019ef-fdc3-4515-8dad-6fcaf742d64b
Two support agents each approve a $70 refund from the same $100 budget. Both read $100, both
think for a few seconds, both approve. The stored balance says $30, which looks fine. $140 left the
building.
without Isolate with Isolate
refunds sent 2 ($140 from $100) 1 ($70)
second agent approved on stale data re-read $30, declined
budget invariant VIOLATED PRESERVED
This is a lost update, and it happens anywhere agents read, decide, then write shared state: ticket queues, CRM records, inventory, calendars, shared plans, budgets, feature flags. Agent frameworks orchestrate who runs when; none of them stop two agents from acting on data that changed under them. Databases solved this 40 years ago with transactions. Agents need the same, plus two things databases never had to care about:
- Thinking takes seconds and costs money. An abort throws away paid LLM tokens, so Isolate picks locking strategies by token cost and reports wasted tokens as a metric.
- Actions can't be undone. Emails, refunds and webhooks are held until commit and sent once, with an idempotency key. An aborted attempt never sends anything.
🚀 Quickstart (60 seconds)
1. Start the server (one coordinator that all your agents share):
docker run -p 127.0.0.1:7070:7070 -v isolate-data:/data ghcr.io/tathagata1010/isolate
This publishes the port on your machine only. Before exposing it to a network, set ISOLATE_API_KEY (see deployment).
Build the image from source with docker build -t ghcr.io/tathagata1010/isolate .. No Docker? Download isolate-server.jar from the latest release and run java -jar isolate-server.jar. Want webhooks too? docker compose up.
2. Wrap the step that reads, decides and writes. Pick your language:
Python · pip install isolate-tx
from isolate_tx import Isolate
iso = Isolate("http://localhost:7070")
def approve_refund(tx):
budget = int(tx.read("refunds/account-42") or 0)
if budget < 7000:
return "declined"
tx.write("refunds/account-42", str(budget - 7000))
tx.after_commit("issue-refund", {"account": 42, "cents": 7000}) # sent only if this commits
return "approved"
# Commits, or retries from fresh data if another agent got there first.
print(iso.run(approve_refund, agent="support-agent", isolation="serializable"))
Async (AsyncIsolate), a with iso.transaction(...) form and a @iso.transactional decorator are in
the Python client docs.
TypeScript / JavaScript · npm i isolate-tx
import { Isolate } from "isolate-tx";
const iso = new Isolate({ url: "http://localhost:7070" });
const result = await iso.run({ agent: "support-agent", isolation: "serializable" }, async (tx) => {
const budget = Number((await tx.read("refunds/account-42")) ?? 0);
if (budget < 7000) return "declined";
await tx.write("refunds/account-42", String(budget - 7000));
await tx.afterCommit("issue-refund", { account: 42, cents: 7000 });
return "approved";
});
Works on Node 18+, Bun, Deno, Cloudflare Workers and Vercel Edge. isolateTool() wraps any Vercel AI
SDK, LangChain.js or Mastra tool. See the TypeScript client docs.
MCP (Claude Code, Claude Desktop, Cursor, VS Code) · no code
claude mcp add --transport http isolate http://localhost:7070/mcp
Claude Desktop, Cursor or any stdio client: {"command": "npx", "args": ["-y", "isolate-tx", "mcp"]}.
Your agents get begin_transaction, read_keys, write_keys, queue_effect, commit_transaction
and friends: a shared scratchpad where two subagents can't claim the same task or clobber the same
plan. See MCP setup.
Java (embedded, no server) · Maven Central
<dependency>
<groupId>io.github.tathagata1010</groupId>
<artifactId>isolate-core</artifactId>
<version>0.1.0</version>
</dependency>
boolean approved = isolate.run(TxOptions.serializable("support-agent"), tx -> {
long available = Long.parseLong(tx.read(BUDGET).orElseThrow());
if (available < 7_000) return false;
tx.write(BUDGET, Long.toString(available - 7_000));
tx.afterCommit("issue-refund", "7000");
return true;
});
Plug in your own systems with a two-method ResourceAdapter, or keep data in PostgreSQL/MySQL with
isolate-jdbc.
Anything else (Go, Rust, Ruby, curl)
TX=$(curl -s -XPOST localhost:7070/v1/tx -d '{"agent":"bash-agent"}' | jq -r .txId)
curl -s -XPOST localhost:7070/v1/tx/$TX/read -d '{"keys":["refunds/account-42"]}'
curl -s -XPOST localhost:7070/v1/tx/$TX/write -d '{"writes":{"refunds/account-42":"3000"}}'
curl -s -XPOST localhost:7070/v1/tx/$TX/commit
Plain HTTP + JSON: the API reference is one page.
3. See the bug, then see it fixed:
python clients/python/examples/refund_race.py # or: node clients/typescript/examples/refund-race.mjs
READ_COMMITTED $140.00 refunded from a $100.00 budget; recorded balance $30.00
refunds issued: 2; retries: 0; invariant: VIOLATED
SERIALIZABLE $70.00 refunded from a $100.00 budget; recorded balance $30.00
refunds issued: 1; retries: 1; invariant: PRESERVED
🧩 What teams use it for
| You're building... | The race Isolate prevents |
|---|---|
| Customer support agents | Two agents refund, credit or close the same account or ticket |
| Sales and CRM agents | Two agents update the same deal stage, owner or discount at once |
| Coding agents and subagents | Two subagents claim the same task or rewrite the same shared plan |
| Ops and SRE agents | Two remediation agents scale, restart or page on the same service; the on-call rule ("at least one person on call") breaks |
| Commerce and booking agents | Inventory oversold, the same seat or slot booked twice |
| Finance and procurement agents | Budgets and approval limits overspent by parallel approvals |
| Multi-tenant SaaS with agents per customer | One customer's agents overwrite each other; namespace keys per tenant (tenant-7/…) |
⚖️ Isolate vs. what you might use today
| Lost updates | Write skew | Effects only after success | Crash recovery | Knows what aborts cost | Works across services and languages | |
|---|---|---|---|---|---|---|
| Nothing (most agent apps today) | ❌ | ❌ | ❌ | ❌ | ❌ | n/a |
| A Redis lock around each tool | ✅ if every path takes it | ❌ | ❌ | ❌ (lock expiry races) | ❌ | ✅ |
| Your database's transactions | ✅ | ✅ (serializable) | ❌ | ✅ | ❌ | Only for data in that one database |
| Durable execution (Temporal and similar) | ❌ | ❌ | ✅ for one workflow | ✅ | ❌ | ✅ |
| Isolate | ✅ | ✅ (serializable) | ✅ (outbox, idempotency keys) | ✅ (log + recovery) | ✅ (token metrics, adaptive locking) | ✅ (HTTP, MCP, Python, TS, Java) |
Durable execution makes one workflow survive crashes; Isolate stops two workflows from corrupting each other. They work well together.
✨ What you get
- Snapshot and serializable isolation for every agent step: consistent reads while the agent thinks, conflicts caught at commit.
- Automatic retries with fresh data, with fair priority so a retried agent can't starve.
- Three locking policies.
optimistic(default),pessimistic(wait instead of retry: 0% wasted tokens in the benchmark), andadaptive(locks only hot keys that have expensive work riding on them). - Post-commit effects as signed webhooks (
X-Isolate-Signature) with stableIdempotency-Keys, retried until delivered, never sent for aborted work. - Durability and recovery. A write-ahead log with group commit (about 5,900 durable commits/s) and crash recovery that finishes half-done commits.
- Safe failover. Epoch fencing stops a stale coordinator from writing after a replacement starts.
- Crashed-agent protection. Idle transactions are aborted so they never hold locks forever.
- Observability. Prometheus
/metrics, including tokens wasted on aborted attempts, plus per-reason abort counts, commit latency and health checks. - Zero runtime dependencies in the engine, the server and both clients. Supply-chain review takes minutes.
🔍 How it works
- Begin: the agent gets a consistent snapshot of the data.
- Work: reads come from that snapshot, so the picture doesn't change while the LLM thinks. Writes and effects stay private.
- Validate: at commit, Isolate checks whether anyone committed a newer version of what this
agent wrote (or, with
serializable, also read). - Decide: if there's a conflict, the attempt aborts and the client retries the step with fresh
reads. Otherwise a
Committedrecord is written to the log. That moment is the commit. - Apply: the writes become visible and the webhooks fire, each exactly once per key. If the process dies, recovery finishes this from the log.
More views: concurrency choices, coordinator failover, transaction lifecycle.
📊 Benchmarks
The benchmark uses simulated agent think time and in-process storage on one coordinator. It's a repeatable comparison of policies, not a production throughput promise. Full report.
Detailed results
1. Lost updates. 16 agents each increment a shared counter 25 times (400 expected).
| Mode | Final value | Lost updates | Wasted tokens |
|---|---|---|---|
No isolation (READ_COMMITTED), what agent frameworks do today | 26 | 374 of 400 😱 | 0% |
SNAPSHOT + optimistic | 400 | 0 | 66% |
SNAPSHOT + pessimistic | 400 | 0 | 0% |
2. Write skew. 200 rounds of the on-call scenario.
| Mode | Rounds where nobody was on call |
|---|---|
READ_COMMITTED | 200 / 200 |
SNAPSHOT | 200 / 200 (snapshot isolation alone can't stop write skew) |
SERIALIZABLE | 0 / 200 ✅ |
3. What safety costs. 32 agents, 80% of work on 4 hot keys, SERIALIZABLE.
| Policy | Wasted tokens | Throughput | p99 latency |
|---|---|---|---|
OPTIMISTIC | 64% | 263 tx/s | 872 ms |
PESSIMISTIC | 0% | 277 tx/s | 872 ms |
ADAPTIVE | 21% | 285 tx/s | 604 ms |
4. Overhead and durability. 8 committing threads, one node.
| Log | Commits/s | p50 | p99 | Commits per disk flush |
|---|---|---|---|---|
| In-memory | 454,343 | 6 µs | 41 µs | n/a |
File, durable fsync (group commit) | 5,926 | 1.4 ms | 1.8 ms | 4.0 |
Next to an LLM call that takes seconds, Isolate's overhead is noise. Group commit lets concurrent commits share one disk flush: durable throughput went from 648 to about 5,900 commits/s, and p99 from 95 ms to under 2 ms (ADR-006).
💡 The most interesting result came from a failure. The first version used textbook wound-wait locking. Under contention it wasted 89% of all tokens with a 25-second p99, worse than no locking at all. Why, and how it was fixed.
🏭 Running it in production
| Need | How |
|---|---|
| Deploy | Docker image, docker-compose.yml, Kubernetes StatefulSet |
| Secure | API keys, HMAC-signed webhooks, effect URLs fixed in server config so agents can't choose them (checklist) |
| Observe | Prometheus /metrics, /v1/stats, /healthz, /readyz |
| Store data in your own DB | isolate-jdbc for PostgreSQL, MySQL, H2 and more |
| Configure | Flags or ISOLATE_* environment variables (reference) |
Current limits, stated plainly:
- One coordinator per log. Failover today is a fast restart with epoch fencing; Raft replication is on the roadmap.
- The server's built-in store replays the log at startup, so startup time grows with history until
log compaction ships. For large data, use the library with
isolate-jdbc. - Isolation is per key. Range and predicate phantoms ("count all open tickets") aren't covered yet.
- Webhooks are at-least-once. Deduplicate on
Idempotency-Keyto get effectively-once.
🧠 Under the hood: the distributed-systems problems Isolate solves
The hard parts
Each of these is a real distributed-systems problem. The HLD and LLD go deeper; here is the short version.
1. Reading a consistent snapshot while commits are still landing
Simple version: you can't take a photo of a room while furniture is being moved in. Isolate waits until the movers are done with everything up to a point in time, then lets you photograph that point.
Engineering version: commits are decided first and applied to adapters after. A reader that picked
"now" as its snapshot could miss a decided-but-unapplied commit and break snapshot isolation. Isolate
tracks in-flight commits and hands out lowest in-flight − 1 as the safe watermark, the same idea
as closed timestamps in Spanner and CockroachDB. Issuing a commit timestamp and registering it as in
flight happen atomically, so no reader can slip in between.
2. One instant that decides everything
Simple version: a wedding is official when the certificate is signed, not when the guests go home.
Engineering version: the Committed log record contains every write and every queued effect
(a redo log). Once it is durable, the transaction cannot abort; everything after is replayable.
Validation runs against an in-memory key → latest commit index updated inside the critical
section, because adapters only learn about writes later. Commits lock hash stripes in sorted
order, so disjoint commits run in parallel and committers can't deadlock.
3. The zombie coordinator
Simple version: an employee goes on a long holiday, gets replaced, then comes back and keeps signing contracts. The fix: every contract must carry the current stamp, and the old stamp is rejected at the door.
Engineering version: a coordinator can freeze (long GC pause, VM migration) and wake up believing
it still leads. Every log record and every adapter write carries the coordinator's epoch. The log
and adapters reject anything older than the highest epoch they have seen. A new leader appends an
EpochStarted record before reading the log, so the zombie is fenced before recovery even begins.
Safety never depends on the zombie noticing it was replaced.
4. Concurrency, priced in tokens
Simple version: in a database an abort costs microseconds. For an agent it throws away every token it paid for. So "should I lock or just retry?" becomes a money question.
Engineering version: three policies per transaction: optimistic, pessimistic, and adaptive,
which locks a key only when contention(key) × tokens at stake ≥ threshold (contention is a moving
average of recent conflicts).
The benchmark exposed two flaws in the textbook approach:
- Wound-wait aborted agents right after they paid for their LLM call. Fix: lazy wound-wait. Wait for a busy lock holder; wound a younger holder only if it is itself blocked, because only blocked transactions can form a deadlock. Still provably deadlock-free.
- An agent that waited for a lock still read its old snapshot, computed on stale data, and
aborted anyway. Fix: reads under a lock are current reads (like
SELECT … FOR UPDATE), and validation compares against the version actually read.
Result: PESSIMISTIC went from 89% → 0% wasted tokens and 25 s → <1 s p99.
Full story in ADR-005.
5. Side effects that can't be rolled back
Simple version: you can cancel a hotel reservation; you can't un-send an email. So cancellable things happen now (and get cancelled on failure), and un-cancellable things wait until the deal is final.
Engineering version: saga steps log their intent before executing, so a crash between "do it"
and "write it down" can't orphan a side effect. Compensations are idempotent and run in reverse.
Irreversible effects sit in a transactional outbox inside the commit record and are delivered
after commit with an idempotency key txId:seq. Delivery is at-least-once; dedup by key makes it
effectively-once.
6. Crashes in the middle of writing
The file log frames every record as length | CRC32C | payload. On open it scans forward and
truncates at the first torn or corrupt record, which can only be the last, unacknowledged one.
Recovery then re-applies committed-but-unapplied writes, re-delivers undelivered effects, and
compensates transactions that died mid-flight.
How it was hardened
Every guarantee here was attacked, not assumed. The process, in the order it happened:
- Benchmark first. The textbook locking scheme wasted 89% of tokens; fixed with lazy wound-wait and current reads (ADR-005).
- Production audit. Five parallel reviewers (concurrency, design, performance, operations,
tests) read the code; every finding was checked by up to three independent skeptics trying to
refute it. 55 findings survived and drove the refactor. Examples:
- an oversized record silently truncated every later commit on restart;
- a failed apply froze every new snapshot for the life of the process;
- restarting with the default lease reused epoch 1, breaking fencing.
- Refactor. The 600-line coordinator split into single-purpose classes with explicit patterns (see the code guide and LLD §13).
- Measure the refactor. Two regressions only showed up in numbers:
- Group commit batched exactly 1 commit per flush on Windows: a write blocks while the file is being flushed. Fixed with a dedicated flusher, now 4–16 per flush.
- Retries collided more often:
LockSupport.parkNanosreturned early on a stale permit and skipped the backoff. Fixed withThread.sleep, which halved aborts.
- Adversarial review of the refactor. 16 more findings, each fixed with a regression test in
ReviewRegressionTest. For example, an interrupted agent thread could close the log file for everyone, and a lost lazy record plus vacuum could make a snapshot read return "absent".
🛠️ Build and test
Requires JDK 21+ and Maven 3.9+ (Python 3.9+ and Node 18+ for the clients).
mvn verify # engine, JDBC, server, CLI
(cd clients/python && python -m unittest discover -s tests) # Python client
(cd clients/typescript && npm ci && npm test) # TypeScript client
java -jar isolate-cli/target/isolate-cli-0.1.0-SNAPSHOT.jar demo # in-process refund demo
mvn -q -pl isolate-bench exec:java -Dexec.args="docs/benchmark-results.md" # benchmark (~1 min)
python tools/diagrams/generate.py # regenerate diagrams
Every docs/diagrams/*.excalidraw file opens at excalidraw.com.
🗂️ Project layout
isolate/
├── isolate-core/ the transaction engine (Java, zero dependencies)
├── isolate-server/ HTTP + JSON API, MCP server, webhooks, metrics
├── isolate-jdbc/ SQL storage adapter (PostgreSQL, MySQL, H2, ...)
├── isolate-cli/ in-process refund demo
├── isolate-bench/ anomaly and contention benchmark with simulated LLM agents
├── clients/
│ ├── python/ pip install isolate-tx
│ └── typescript/ npm i isolate-tx
├── deploy/kubernetes/ StatefulSet + Service
├── docs/ requirements, HLD, LLD, code guide, ADRs, API, MCP, deployment
└── tools/ diagram generator, webhook echo server
📚 Docs
| If you want to... | Read |
|---|---|
| Call Isolate from any language | HTTP API |
| Give MCP agents a shared transactional scratchpad | MCP setup |
| Use it with LangGraph, CrewAI, OpenAI Agents SDK, Vercel AI SDK | Framework integrations |
| Deploy, secure and monitor it | Production guide |
| Keep agent data in your SQL database | JDBC adapter |
| Understand the requirements and design | Requirements · HLD · LLD |
| Read the code in 30 minutes | Code guide |
| Know why each big decision was made | ADR-001 commit protocol · 002 isolation · 003 HA · 004 clocks · 005 token-priced locking · 006 group commit · 007 reconciliation |
🧭 Roadmap
- Engine: MVCC, three isolation levels, sagas, outbox, WAL with group commit, fencing, recovery, lazy wound-wait, adaptive policy, two adversarial reviews
- Reach: HTTP server, MCP server, Python and TypeScript clients, JDBC adapter, Docker, Kubernetes, Prometheus
- Log compaction and snapshots for fast restarts
- Multi-tenancy: API keys per tenant, quotas and token budgets
- OpenTelemetry tracing, Go and Rust clients
- Replication and sharding: Raft-replicated log per shard, then cross-shard transactions
- Semantic conflicts: an LLM judge for writes that touch different keys but contradict each other
- Proof: TLA+ spec of commit and failover; deterministic simulation and fault-injection testing
❓ FAQ
My agents are in Python. Do I need to know Java?
No. Run the Docker image and use the Python or TypeScript client, or plain HTTP. Java is only how the engine is built.
Why not just put everything in PostgreSQL?
If all your agents' data lives in one database, use its transactions; they're great. Isolate is for the common case where agents work across APIs, tools and services that don't share one transaction, and where you also need post-commit effects, retries with fresh data and token-cost visibility.
Where should the LLM call go: inside or outside the transaction?
Inside, when the decision depends on shared data: a conflict re-runs the call with fresh data. Use
policy: "pessimistic" on hot keys so agents wait instead of re-paying for the call. See
integrations.
What happens if an agent crashes mid-transaction?
Nothing it wrote becomes visible, none of its effects are sent, and after the idle timeout (default 2 minutes) its locks are released.
What if the Isolate server crashes?
Committed work is in the log. On restart, recovery re-applies anything half-finished and re-sends undelivered webhooks with the same idempotency key. Uncommitted work is discarded, and clients retry.
Why not two-phase commit?
Most external systems can't "prepare" a change, and 2PC blocks every participant if the coordinator dies at the wrong moment. Isolate decides in its own log and treats external systems as replayable targets. See ADR-001.
How do I plug in my own system in Java?
Write a ResourceAdapter with two calls: readAt(id, timestamp) (newest version at or before a time)
and apply(id, value, commitTs, txId, epoch) (an idempotent write that rejects stale epochs). A version
column and a conditional update are enough. See LLD §10 and the JDBC adapter as a
reference.
🤝 Contributing
Issues and PRs are welcome. A client for another language, Testcontainers runs for more databases, and framework examples are great first contributions. See CONTRIBUTING.md, SECURITY.md and the code of conduct.
If Isolate saved your agents from a bad day, a ⭐ helps others find it.
License
isolate-txnpm install isolate-tx