Also known as the build stage of the SDLC, coding focuses on the writing and programming of a system. The Zones in this category take a hands-on approach to equip developers with the knowledge about frameworks, tools, and languages that they can tailor to their own build needs.
A framework is a collection of code that is leveraged in the development process by providing ready-made components. Through the use of frameworks, architectural patterns and structures are created, which help speed up the development process. This Zone contains helpful resources for developers to learn about and further explore popular frameworks such as the Spring framework, Drupal, Angular, Eclipse, and more.
Java is an object-oriented programming language that allows engineers to produce software for multiple platforms. Our resources in this Zone are designed to help engineers with Java program development, Java SDKs, compilers, interpreters, documentation generators, and other tools used to produce a complete application.
JavaScript (JS) is an object-oriented programming language that allows engineers to produce and implement complex features within web browsers. JavaScript is popular because of its versatility and is preferred as the primary choice unless a specific function is needed. In this Zone, we provide resources that cover popular JS frameworks, server applications, supported data types, and other useful topics for a front-end engineer.
Programming languages allow us to communicate with computers, and they operate like sets of instructions. There are numerous types of languages, including procedural, functional, object-oriented, and more. Whether you’re looking to learn a new language or trying to find some tips or tricks, the resources in the Languages Zone will give you all the information you need and more.
Development and programming tools are used to build frameworks, and they can be used for creating, debugging, and maintaining programs — and much more. The resources in this Zone cover topics such as compilers, database management systems, code editors, and other software tools and can help ensure engineers are writing clean code.
Terry: A Live File Tree and Review Gate for Claude Code
Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't
A cyber-security engineer reviews a log file and notices a strange behavior. When PHP’s memory ceiling is reached, the engine fires a hard request to kill the process. That violent stop, he found, had an unfortunate consequence; it left the PHP server open to remote commands. The engineer paused. In theory, if a hacker could control what was written into that memory space right before the crash, they might force the engine to execute their own commands during the cleanup loop. To turn that dangling pointer into a real system breach over a live web connection, an attacker would have to perform digital acrobatics. They would need to send precise, multi-part payloads — crafted down to the exact byte — to groom server memory, predict chunk allocations across network latency, and time the exact microsecond the engine ran out of memory. A human hacker trying to build a working exploit faced hundreds of hours of manual trial and error. The sheer complexity of the exploit was the gate to its execution. The engineering team concluded that fixing the flaw risked breaking runtime performance or shattering backward compatibility for thousands of third-party C-extensions. Their finding: Low severity. Highly complex. Practically unexploitable. People evaluated the risk, weighed the cognitive friction required to weaponize it, and concluded that PHP was safe behind the wall of Complexity Defense — the assumption that a vulnerability is functionally harmless because exploiting it is too hard, too tedious, or too time-consuming. For two years they were right. There were no recorded incidents of attempting a breach using this specific exploit. The Alarm Goes Off In August 2026, researchers fed the Zend Engine's source code into frontier AI reasoning models. These AI engines didn't care about human fatigue, backward-compatibility debates, or the difficulty of the math. They ingested the constraints, mapped thousands of execution branches in parallel, and solved the multi-variable memory layout puzzle in seconds. By afternoon, the "unexploitable" low-severity ticket from 2024 was solved, registering a vulnerability that exposed about 70% of global websites to remote control. The PHP Foundation published PHP2Shell (CVE-2026-109618 and CVE-2026-109619), triggering a global wave of emergency site shutdowns and patching. The Dual Engine: A Mirror of Human Intent Commentary on the discovery of this vulnerability ran the spectrum. Half the headlines warned that AI was being weaponized to break the internet; the other half praised AI researchers for saving us from a silent zero-day. Both narratives miss the fundamental reality. What happened with PHP2Shell has nothing to do with sci-fi narratives of apocalyptic AI or automated digital utopias. AI is neither the hero nor the villain here — it is an intent-agnostic cognitive force multiplier. Our cybersecurity engineer applied AI to find and fix vulnerabilities. The potential hacker could use AI to deliver exact exploit instructions. The Benefit: Rapid Diagnostic Exposure For defensive teams, AI is the ultimate diagnostic lens. AI democratizes high-tier code analysis, allowing defenders to parse millions of line interactions, surface hidden architectural defects, and fix them before they are weaponized in the wild. The Risk: The Democratization of Exploits The exact capability that lets an AI model find a flaw also allows it to synthesize the exploit. Historically, even if a bad actor discovered a subtle memory bug, actually building a working exploit required world-class reverse-engineering talent. AI erases that barrier to entry. It takes high-complexity edge cases and translates them into turn-key attack vectors for anyone with access to sufficient compute. Two caveats keep this honest. First, the defender's window was short. Reporting indicates details leaked, a proof-of-concept tool surfaced, and exploitation attempts followed the disclosure. A head start measured in days is not a comfortable margin. Second, the contest is asymmetric. Defenders have to patch millions of instances. Attackers only need one unpatched entry. Engineering Takeaways: The End of "Security Through Obscurity” The PHP2Shell event isn't proof of autonomous AI systems running amok; it is proof that cognitive friction is no longer a valid security control. Whether you are managing an engineering team or advising executive leadership, the collapse of Complexity Defense forces three immediate operational shifts: Kill the "Low Severity/Hard to Exploit" Triage Category: "Too hard to weaponize" is obsolete. If your security backlog contains technical debt for flaws that were marked "low priority" because building an exploit seemed too complicated — revisit them now.“Time-to-Patch” is the Modern Security Metric: The gap between "bug known" and "working exploit" has collapsed. What matters now is how quickly your environment can absorb an upstream fix without breaking production. Companies that can't answer "which of our systems run PHP" in an hour have already lost time. Passive security methods will be quickly overwhelmed by autonomous agents.Proactive AI Auditing is Mandatory: Waiting for third-party disclosures or CVE reports is a risky strategy. Point AI-assisted analysis at your proprietary code and your critical dependencies. Scanning once is not enough. This has to run continuously, not on an annual audit cadence. Death of the Complexity Defense The organizations that thrive in this new landscape will acknowledge the new requirement for speed-to-discover and speed-to-patch metrics. Security control can no longer be practiced on a periodic cadence. Using AI to discover and secure vulnerabilities will become essential to security practice. The doom vs. utopia conversation, beloved by the media, is irrelevant to this discussion. AI has no intent; it’s an intent multiplier and facilitator. It’s open to the benevolent work of the researcher and the malevolent intent of the hacker. PHP2Shell was a disruptive, painful event for engineering teams worldwide, but it stripped away a comforting illusion: that software can be protected by how hard it is to attack. Friction that once protected us is gone, and the old categories of "low priority" and "practically unexploitable" need rewriting. The Complexity Defense is dead in the face of AI.
Most of our tickets end the same way now. Someone copies the issue text into Claude Code or Codex, adds “look at the memory notes first,” waits, pushes a branch, opens a PR, and pastes the link back into the ticket. The work is done by the agent. The glue around it is done by hand, and nothing records which run produced which PR, what it cost, or why the first try failed. So we moved the glue into Origin. An issue now has a Start with button. It hands the issue to an agent that runs on your own machine, in its own worktree, and the run is recorded on the issue: who ran it, which agent and model, how long, what it cost, how many lines, and whether its PR was merged. This post shows how it looks and what it does. A separate write-up covers how we built it. One List, Every Source Issues come from five places and land in one list: GitHub and GitLab issues (two-way sync), Jira, issues created in Origin, security alerts from Dependabot and code scanning, and TODOs that agents left in the repo’s memory notes. The list sorts by priority and filters by repo, source, and assignee. Each row shows the source, labels, priority, and, once an agent has worked on it, the number of sessions and the AI cost. The host stays the owner of what it owns. Title, body, labels, assignees, and open/closed come from GitHub or GitLab, and Origin writes assignees back. Origin owns the states the host does not have: in progress, in review, and blocked. Start With an Agent The menu lists the agents Origin can launch headless: Claude Code, Codex, Gemini CLI, Cursor, Copilot CLI, and Antigravity. Pick one, and you get the Start dialog. The prompt is built from the issue and the repo’s memory (here, 4,418 characters and 10 lines of memory), and you can edit it before you start. Below is the exact command the button runs, so you can run the same thing from a terminal: Shell origin issue start OR-44 --agent claude --background Without Run in the background, Origin opens a terminal in your checkout with the agent and the prompt in it, and you work as usual. With it, there is no terminal. The agent runs headless in a new worktree on branch issue/OR-44-…, so your own checkout can stay dirty. When the agent exits cleanly, Origin pushes the branch and opens a PR. It never merges and never force-pushes. The run happens on your machine, with your agent CLI and your agent’s account. Origin’s server never runs code. The button opens a getorigin:// link that carries only the repo and issue IDs; the Origin CLI on your machine reads the issue with your own key and starts the agent. The full log stays in ~/.origin/agent-runs/. The server gets the status, the exit code, and the last few log lines. Before It Starts: Is the Agent Signed In, and Is the Task Clear? A signed-out Claude Code exits in a second with “Not logged in,” and for a while that run still looked completed. Now a background run first checks that the agent is signed in. If it is not, nothing starts, no worktree is made, and the issue shows a failed run with the reason. The Agents page shows the same check per machine; above, the last background Claude run on this MacBook could not sign in. The second check is about the task. A one-line issue leaves the agent guessing, and a background agent has nobody to ask. So before a background run, Claude or Codex reads the repo in a read-only mode, without hooks and without saving a session, and answers one question: is this clear enough to do? If yes, it writes a short brief (files and approach) into the prompt. If not, it asks up to three questions. They appear on the issue; nothing starts, and you answer on the page or with: Shell origin issue answer OR-44 "Keep v1 readable; consumers must handle both" A run can also stop and ask halfway. When you answer, the next start resumes the same agent session (claude --resume, codex exec resume) if that session is on this computer, so the agent keeps what it already read. Otherwise it starts fresh with every answer in the prompt. Every Attempt Stays on the Issue This issue was not written by a person. Claude Code left it as a TODO in the repo’s memory during an earlier session (“the header’s tokens, cost and tools chips still come from the old session totals”), and Origin turned it into an issue. Antigravity took it twice. The first run failed, and the table says so; before we recorded runs, a run that died before the agent’s first hook fired left no trace at all. The second run worked for 30 minutes and opened PR #2487 with +846 −70 lines in 9 files. The issue moved to In review on its own. Each row links to the captured session, so you can read every prompt, tool call, and diff of that run. Status follows the work: start or claim → in progress, PR open → in review, PR merged → closed, PR closed unmerged → back to in progress. An agent can also end with a line like [Origin: Outcome] blocked — which schema version?, and the issue goes to blocked with that question on it. Race Two Agents on the Same Issue If you are not sure which agent is best for a task, give it to two to four of them. Each runs in the background on its own branch from the same base, and each one that finishes cleanly opens its own PR. Merge the best one, and the issue closes. This one was a Dependabot alert for source-map-js. Origin turned it into an issue with acceptance criteria (the lockfile no longer resolves a vulnerable version, tests pass). Claude’s PR was merged at $0.50. Codex’s PR was closed; it cost $0.96 and used about ten times the tokens. Over a few dozen issues, that table tells you which agent to give which kind of work. For closed issues, the page also gives a origin benchmark replay-tasks command, so you can replay the issue on other agents later and grade them against the tests the merged PR added. Agents That Pick Up Work Themselves The Start button is one way in. The other is the queue. Origin’s MCP server gives agents list_tasks, take_task, finish_task and release_task. An agent in a session can take the next ready issue, and two agents can never take the same one: a claim is a single conditional database write, so exactly one of them wins, and the others get “claimed”. A claim is a lease (30 minutes by default) renewed by the session’s heartbeat. If the agent dies, the lease runs out, and the task is free again, without a cleanup job. Issues with open dependencies are not served. What It Will Not Do Run anything on Origin’s servers. The agent runs on your machine, with your installed CLI and your account.Use a blanket permission bypass. Each agent gets the narrowest unattended mode it has: Claude’s --permission-mode auto, Codex’s workspace-write sandbox, a per-run Antigravity project allowed only git and read-only commands with no network, a scoped .cursor/cli.json.Merge, or force-push. It opens a PR and stops.Run forever. Background runs stop after 120 minutes by default, together with every process the agent started.Send the whole log to the server. Only the status and the last lines. Try It You need the Origin CLI, and at least one agent CLI signed in. Run origin url-handler install once so the Start button can reach your machine, then open Issues and press Start with. From a terminal, it is origin issue start <id> --agent codex --background, origin issue race <id> --agents claude,codex and origin issue runs to see what is running.
Summary After six months of writing microservices with GitHub Copilot, I learned that the quality of generated code correlates directly with prompt specificity. Vague requests like "create a REST endpoint" resulted in code that ignored idempotency, retry logic, and failure scenarios — the exact behaviors that cost me debugging hours in QA. This article walks through a real order-processing example, showing how structured prompts that describe boundaries, failure modes, and test criteria produce production-grade code faster than either one-liners or guesswork. The Wake-Up Call Last spring, our team started using GitHub Copilot to accelerate Java microservice development. At first, I followed the obvious path: describe the feature in a sentence, accept the first suggestion, and move on. It worked until it didn't. I asked Copilot to "publish OrderCreated events to Kafka." It generated code that called producer.send() and hoped the message went through. In testing, I discovered that if the process crashed after saving the order but before publishing the event, the message never left the database. In production, this meant inventory overages and customer complaints about orders that appeared to be placed but never shipped. The real issue wasn't Copilot. It was me. I'd asked a one-line question and gotten a one-line answer. I'd skipped the part where I specify what should happen when infrastructure fails. That lesson drove me to develop a prompt structure that forces me to think clearly before asking Copilot to code. A Prompt Pattern That Works Over the following months, I refined this template and tested it on five microservices in our system: Plain Text Act as a senior Java engineer. In [module], implement [behavior]. Constraints: [Java/Spring versions, architecture, API contract]. Failures: [timeouts, duplicates, invalid input, partial outages]. Tests: [unit, component, contract, performance acceptance criteria]. First show the design and assumptions. Then make a small change. Do not change unrelated files. Explain tradeoffs and how to verify. The key improvements: Constraints force me to state what versions, frameworks, and architectural decisions apply.Failures push me to name specific failure modes before writing a line of code.Tests require me to specify how I'll know the code works under stress. This structure reduced my QA cycle time by roughly 30% because the generated code already anticipated the edge cases I would have caught later. 1. Start With the Domain, Not the Controller The Mistake I Made Early on, I asked Copilot to "create order service, classes." It generated a REST controller, a service, a repository, and a JPA entity all in one go. The code compiled and my first test passed. But when I integrated it with our actual domain model (which had Order aggregates, ValueObjects for OrderId, and explicit domain rules), the generated code was incompatible. The controller was mixing HTTP concerns with business logic. I spent half a day refactoring. The Better Approach Instead, I now ask: Plain Text Review this Spring Boot order module. Identify the Order aggregate, value objects, domain rules, and application ports. Keep HTTP, Kafka, database, and gRPC types outside the domain layer. Apply single-responsibility and dependency-inversion principles. Propose a minimal package structure before generating code. Do not add interfaces unless a real dependency boundary needs one. This time, Copilot proposed interfaces like: Java public interface OrderRepository { Optional<Order> findById(OrderId id); void save(Order order); } public interface InventoryGateway { InventoryDecision reserve(Order order); } When our gRPC client changed later (we switched from a proprietary RPC system to gRPC), the domain layer didn't need to know. We updated the adapter, not the Order class. That's when I realized domain-driven design isn't just academic; it's a practical time-saver when integration details change. Lesson Learned Don't ask for a complete microservice. Ask for the boundaries first. Code generation is faster when you've already sketched the architecture. 2. Make REST Behavior Explicit What I Tested and Found I deployed an idempotent POST endpoint that used an in-memory map to track Idempotency-Key headers. During our first load test with 5 replicas, a customer's retry request hit a different pod and got a duplicate response. The in-memory map only existed on the first pod. Copilot had done what I asked: "support idempotency." I hadn't asked it to think about distributed systems. The Refined Prompt Plain Text Implement POST /v1/orders in Spring Boot. Request: customerId, line items, delivery window. Return 201 with order ID and Location for a new order. Use Jakarta Bean Validation and consistent ProblemDetail errors. Support an Idempotency-Key header with durable deduplication. Return the stored result for a retry with the same key and payload; reject reuse of the same key with a different payload. Add MockMvc tests for 201, 400, 409, and identical retries. State the database uniqueness/transaction assumptions first. This time, Copilot proposed storing the key and request fingerprint in the database, with a unique constraint. It generated a test that simulated two concurrent first requests and verified that only one order was created. That test caught a race condition I would have missed. What Changed API contracts should be explicit before implementation. Include the request/response schema, HTTP status codes, error types, and idempotency strategy. Copilot's code quality jumped when I provided that context. 3. Event Delivery and the Outbox Pattern The Real Problem Telling Copilot to "publish OrderCreated events" results in this anti-pattern: Java orderService.save(order); kafkaProducer.send(orderCreatedEvent); If the second line fails, you have an order in the database but no event. Downstream services waiting for OrderCreated will never process this order. I saw this in production. A Kafka broker went down for 40 seconds. Orders were saved, events were lost, and our fulfillment system got out of sync. The Transactional Outbox Solution I now ask Copilot for the outbox pattern explicitly: Plain Text After order creation, publish OrderCreated using the transactional outbox pattern. Save the order and outbox row in one DB transaction. Use eventId, aggregateId, version, occurredAt, and schemaVersion. Provide a relay design and an idempotent consumer using eventId. Assume at-least-once delivery, retries, and out-of-order arrival. Show duplicate-event and relay-restart component tests. Copilot now produces: Java @Transactional public void createOrder(Order order, OrderCreatedEvent event) { orderRepository.save(order); outboxRepository.save(new OutboxEvent( UUID.randomUUID().toString(), // eventId order.getId().value(), // aggregateId order.version(), Instant.now(), event )); } And a relay job that periodically scans for unpublished events and sends them to Kafka. A component test verifies that if the relay crashes mid-send, restarting it publishes the message again without duplication (using eventId idempotence). Impact The outbox pattern takes one extra database round-trip. Our benchmarks showed <2ms overhead per order, negligible compared to network time to Kafka. But it eliminated a class of bugs: lost events. 4. gRPC and Timeout Propagation A Real Scenario Our order service calls an inventory service over gRPC with a 5-second timeout. The inventory service itself calls a warehouse database with a 10-second timeout. During a database slowdown, the inventory service exhausted its connection pool, and every call started timing out. But from the order service's perspective, each gRPC call was simply hitting the 5-second limit. We saw no degradation in error rates—just slow requests. It took three hours of tracing to realize the inventory service was queued up behind connection pool exhaustion. Copilot Prompt for Timeout Propagation Plain Text Implement a gRPC stub that calls inventory-service. Pass the request deadline from the calling context (gRPC deadline). If the context has <500ms left, fail fast instead of sending the RPC. Add observability: log deadline exceeded, pool exhaustion, and retries. Write component tests for: normal operation, deadline exceeded, connection pool exhaustion, and cascading slowdown. Use Micrometer metrics to expose connection pool state. Copilot now generates code that: Respects context deadlines and fails fast when time is running out.Metrics that expose connection pool usage, helping us spot saturation before it causes timeouts.A test that simulates pool exhaustion and verifies the error message and metrics. That test caught a misconfiguration in our test environment where the pool was sized for 10 but we were load-testing with 100 concurrent requests. Key Insight Timeouts are not just about infrastructure. They're about propagating caller intent through the call stack. When Copilot understands that architecture, it generates better code. 5. Testing: Layers and Trade-Offs Where I Went Wrong Initially Copilot can generate end-to-end tests that spin up Kafka, a database, and a gRPC stub. The tests pass and feel reassuring. But they're slow: 30 seconds per test, and they only catch integration bugs, not domain logic bugs. I had end-to-end tests for the idempotent POST endpoint. They passed locally. But when we deployed to staging with real infrastructure, a DNS timeout caused the retry logic to fail. The end-to-end test didn't simulate that. Structured Test Prompts I now ask Copilot to generate tests in layers: Unit tests: Plain Text Write unit tests for OrderService.createOrder(). Test: happy path, zero items (validation), duplicate order ID. Mock all dependencies; verify calls and return values. Use a test fixture factory for Order objects. Component tests: Plain Text Write a component test for POST /v1/orders. Use @WebMvcTest and mock external services (Kafka, inventory). Test: 201 for valid request, 400 for invalid input, 409 for duplicate. Verify the outbox record was created; simulate relay delay. Test idempotency: send same request twice, verify one order. Do not spin up real databases or message queues. Contract tests: Plain Text Write a contract test between order-service and inventory-service. Order sends a gRPC request; inventory responds with a decision. Test: success, timeout (500ms), invalid response. Use Pact to document the contract; publish results to the broker. Performance tests (with SLO context): Plain Text Create a k6 workload for POST /v1/orders. Target: p95 latency <200ms, error rate <0.1%, throughput >100/sec. (These are our actual SLOs from our runbook.) Use realistic unique idempotency keys and payload sizes. Track database latency and Kafka publish latency separately. Run from a staging environment; compare against baseline. Result Each layer catches different bugs. Unit tests catch logic errors. Component tests catch integration wiring errors. Contract tests catch API mismatches. Performance tests catch scaling issues. By being specific about which layer, I got Copilot to generate focused, fast tests that actually caught bugs before production. 6. Kubernetes Deployment With Observability Baked In The Hard Lesson We deployed our order service to Kubernetes without explicitly configuring liveness and readiness probes. The pod looked healthy (processes running), but one instance had an exhausted connection pool and was queued on every request. Kubernetes sent traffic to it anyway. Customers saw timeouts. The Deployment Prompt Plain Text Create a multi-stage Dockerfile for this Java service. Run as non-root; use a small maintained runtime image (e.g., eclipse-temurin:21-jre). Then generate Kubernetes Deployment, Service, and probes. Separate startup, readiness, and liveness checks. Startup: just verify the application has started. Readiness: verify the service can accept traffic (check pool, dependencies). Liveness: verify the process is alive; avoid false restarts. Add resource requests and limits based on our measurements: - requests: CPU 500m, memory 512Mi - limits: CPU 1000m, memory 1Gi Graceful shutdown: 30-second termination grace period. Do not put secrets in images or manifests. Document the deployment assumptions and how to roll back. Copilot generated a Deployment that: Used separate probe endpoints (the readiness probe actually checked the connection pool).Set an appropriate grace period for draining in-flight requests.Exposed metrics and environment variables for configuration. When we deployed this to staging, readiness probes started failing when the connection pool approached saturation, and Kubernetes automatically removed the pod from service. No more timeouts from saturated instances. 7. Service Mesh Configuration and Retry Budgets Where Layers Collided Our infrastructure team added a service mesh (Istio) to handle mutual TLS and observability. The default configuration retried failed requests at the mesh layer. Our order service was also configured to retry on 503. Customers were seeing duplicate orders because we were retrying POSTs twice. The Proper Prompt Review the order-service mesh configuration for retries. Do NOT retry non-idempotent POSTs at the mesh layer. Only retry GET and idempotent operations. Set mesh timeout to 10s, app timeout to 5s (so app timeout fires first). For each outbound route, document why retries are/are not safe. Explain how retries interact with the outbox pattern relay. Show a staged rollout plan with observable signals (error rate, latency). Copilot proposed a configuration where: The mesh did NOT retry POSTs.The app (order service) did NOT retry the Kafka publish (handled by the outbox relay instead).Each timeout was explicitly documented with justification. When a new engineer joined, they could read the config and understand the design intent, not just the mechanics. 8. Observability From the Start Operational Insight Six months into production, we realized our dashboards didn't show us what we actually needed to know. We had request latency (good), but not whether latency was from database queries, Kafka, or gRPC calls. We had error rates, but not which downstream service was failing most often. Copilot Prompt for Observability Plain Text Instrument the order-service with OpenTelemetry. Track: request rate, errors (with type), latency (p50/p95/p99), database query duration, Kafka publish latency, gRPC call latency. Use low-cardinality labels (e.g., operation, status). Do NOT add orderId as a metric label (too high cardinality). DO add orderId to traces and logs. Create an OpenTelemetry collector config and a Grafana dashboard. Document SLOs: p95 latency <200ms, error rate <0.1%. Show alerting rules for SLO violations. Copilot generated Prometheus metrics and a dashboard that showed: Order creation latency broken down by component (database, Kafka, gRPC).Kafka lag (how far behind the relay was).gRPC deadline exceeded errors vs. actual errors. That visibility let us spot that our inventory gRPC calls were taking 150ms on average, while database queries took 20ms. We optimized the gRPC client (connection pooling, deadlines), and p95 latency dropped from 350ms to 150ms. 9. Use Copilot as a Skeptic, Not a Final Authority The Mindset Shift The most valuable prompt isn't "Is this production-ready?" It's "Find the bugs": Plain Text Review this change as a skeptical senior engineer. Find: contract changes, race conditions, retry amplification, PII leaks, missing negative tests, and SOLID violations. For each issue cite file/line, risk, and a focused fix. Separate confirmed findings from assumptions. Do not claim tests passed unless you ran them yourself. Copilot actually flagged a subtle bug in our idempotent POST: if two concurrent requests with the same Idempotency-Key arrived while the first was still processing, the database unique constraint would cause a collision, but the error handling code assumed a parse error, not a collision. We would log it as a client error when it was a collision. A human senior engineer would have caught this in code review. But Copilot caught it when I asked it to think like a skeptic. What I'd Do Differently Now For a Brand New Microservice Sketch the domain model first (Order, OrderId, OrderStatus).Define the external contracts (REST API schema, events, gRPC proto).Ask Copilot to propose package structure and interfaces.Prompt for implementations one behavior at a time (create, update, cancel).For each behavior, ask for domain logic, then REST layer, then event publishing.Ask for tests before asking for code (test-driven).Review the generated code with the same skepticism you'd use for a new team member. For an Existing Microservice Identify a behavior you want to change (e.g., add retries, change a timeout).Ask Copilot to review the current code and propose changes.Specify the constraints and failure modes for the change.Ask for a test that verifies the change under stress.Run the test locally and against staging before merging. For Team Knowledge Copilot is a force multiplier for teams with clear architecture and design patterns. If your team has well-documented domain models, API contracts, and deployment standards, Copilot will amplify those. If you don't have those things, Copilot will amplify confusion.
Over the years, as the software industry became aware of the problems that come with authorization logic embedded in application code, moving that logic out of the application has gradually become the accepted solution. In this model, as described by the OASIS XACML standard back in 2003, a Policy Decision Point (PDP) holds the policies and makes the decisions, and a Policy Enforcement Point (PEP) inside the application consults the PDP and enforces its decision. This separation created a new need, namely a common way for the PEP to consult the PDP. Every PDP (OPA, Cerbos, Topaz, Axiomatics, …) offers its own API and its own request structure. As a natural consequence, applications become dependent on one vendor’s API, and replacing the PDP means rewriting every enforcement point. The same fragmentation affects libraries. Every PDP needs its own SDK for every language and framework, so many pairs are never covered, and the PDP you choose may simply have no library for your stack. And API gateways, identity providers, and SaaS products cannot offer a “bring your own PDP” option without building a separate integration for each vendor. In this article, I introduce AuthZEN, a standard that addresses exactly these problems, and authzen-enforcer, the open-source Java SDK I developed to put it into practice. After a look at the specification and at Keycloak as an AuthZEN PDP, I show how the SDK brings AuthZEN to Java and Spring Boot applications. What Is AuthZEN? AuthZEN is the OpenID Foundation’s effort to standardize how PDPs and PEPs, in the words of the specification, communicate authorization requests and decisions to each other without requiring knowledge of each other’s inner workings, and in doing so provides the missing common language between PEPs and PDPs. Its specification, the Authorization API 1.0, was developed by the AuthZEN working group and approved as an OpenID Final Specification in January 2026. The standard deliberately says nothing about how policies are written or stored; it standardizes only the communication between the two parties, that is, what the PEP asks, what the PDP answers, and how the PEP discovers the PDP’s endpoints. How the PEP authenticates is left to established mechanisms, with OAuth 2.0 recommended. In short, just as OpenID Connect standardized authentication by giving applications a standard way to answer who is this user?, AuthZEN does the same for authorization, providing a standard way to answer is this user allowed to do this? A Look at the Specification The Authorization API is a short and readable specification. Its core fits into a few ideas, and each of them answers one of the problems described above. Four Entities and a Decision Every access question is built from the same four parts. The subject is who wants access, the action is what they want to do, the resource is what they want to do it to, and the optional context describes the circumstances, such as the time of the request, the client’s IP address or whether the user signed in with multi-factor authentication. Subjects and resources are identified by a type and an id, an action by its name, and anything else travels in properties. The answer is a decision, true or false, optionally with a context of its own that can carry reasons or ask for a step-up authentication. JSON { "subject": { "type": "user", "id": "alice", "properties": { "department": "finance" } }, "action": { "name": "read" }, "resource": { "type": "document", "id": "123" }, "context": { "time": "2026-11-12T16:30:00Z", "ip": "203.0.113.7" } } JSON { "decision": true } Neither side of this exchange reveals how the PDP works. The request says nothing about how the decision is reached, so whether the policies follow RBAC, ABAC, ReBAC, or a mix of them, the application asks the same question in the same shape. The response, in turn, is deliberately minimal. A single boolean is all the PEP needs to enforce the decision, while all reasoning about policies stays inside the PDP. This is what removes the coupling to a single vendor, since replacing the PDP changes neither the question the application asks nor the way it enforces the answer. Note that a deny is not an error. The PDP answers 200 OK with "decision": false, while a 401 or 403 means that the PEP itself was not allowed to ask. Three Ways to Ask The Authorization API offers three ways to ask the PDP for decisions. The first is the Access Evaluation API at /access/v1/evaluation, which returns a single answer to a single question, such as can Alice read document 123? HTTP POST /access/v1/evaluation { "subject": { "type": "user", "id": "alice" }, "action": { "name": "read" }, "resource": { "type": "document", "id": "123" } } JSON { "evaluations": [ { "decision": true }, { "decision": false } ] } By default, every item is evaluated. With options.evaluations_semantic set to deny_on_first_deny or permit_on_first_permit, the batch stops at the first deny or the first permit, much like && and ||. A bulk delete is a natural fit for deny_on_first_deny. Either Alice may delete every selected document, or the operation does not run at all, so there is no point in evaluating the rest once one is denied. HTTP POST /access/v1/evaluations { "subject": { "type": "user", "id": "alice" }, "action": { "name": "delete" }, "evaluations": [ { "resource": { "type": "document", "id": "123" } }, { "resource": { "type": "document", "id": "456" } }, { "resource": { "type": "document", "id": "789" } } ], "options": { "evaluations_semantic": "deny_on_first_deny" } } JSON { "evaluations": [ { "decision": true }, { "decision": false, "context": { "reason": "deny_on_first_deny" } } ] } The PDP stopped at the second document, so the third has no decision. A PEP has to treat such a missing decision as a deny. Runnable versions are in the examples of authzen-enforcer, the Java SDK introduced below, with both semantics in the plain Java example and the bulk delete above in the Spring Boot example. The third is the Search APIs, three endpoints below /access/v1/search/, which turn the question around. Leave out the ID of the entity you are looking for, and the PDP returns the ones it would permit. The resource search below answers: which documents can Alice read? HTTP POST /access/v1/search/resource { "subject": { "type": "user", "id": "alice" }, "action": { "name": "read" }, "resource": { "type": "document" } } JSON { "results": [ { "type": "document", "id": "123" }, { "type": "document", "id": "456" } ] } Subject search (who can read document 123?) and action search (what can Alice do with document 123?) work the same way, and large results come page by page. A search result is not a decision, so access is still enforced with an evaluation. Finding the PDP and Trusting the PEP A PEP does not need the URLs of these endpoints one by one; it can discover them. The specification recommends that a PDP publish a metadata document at /.well-known/authzen-configuration that lists the endpoints it offers, so knowing the PDP's base URL is enough for a PEP to find out where to send each request. An endpoint missing from that metadata tells the PEP that the PDP does not offer the API, and a PDP without metadata is reached at the default paths shown above. The specification also asks the PDP to authenticate the calling PEP, and the PDP trusts the PEP for the values it sends, the subject included. In practice, this means that the PEP talks to the PDP with its own identity, such as a service account, and not with the end user's token. Why the Shape Matters Each of these choices maps back to the problems described at the beginning. The API itself is transport-agnostic, and other bindings such as gRPC may be defined as profiles, but every compliant PDP must implement the HTTPS binding with JSON. A shared vocabulary on top of a transport that every PDP speaks means that an application written against one PDP works against another, and on the application side, switching becomes a matter of configuration. A PEP library written once for a language or framework can work with any compliant PDP, so a new library is no longer needed for every vendor, even if details such as how the PEP authenticates still differ from one PDP to another. And an API gateway or identity provider can implement the PEP side once and let its customers bring their own PDP, as gateways such as Kong, Envoy and Tyk already did in the AuthZEN interop events. Who Supports AuthZEN Today? At the time of writing, close to twenty implementations, among them Axiomatics, Cerbos, Topaz, PlainID, Ping Identity and WSO2, have published their results from the interoperability events of the AuthZEN working group. These results were produced against pre-final drafts of the specification, and a conformance certification program is still in development. This article focuses on Keycloak. It is the identity provider many Java teams already run, and since version 26.7.0 it acts as an AuthZEN PDP as an experimental feature (--features=authzen). It evaluates each request against the resources, scopes, and policies defined under Authorization Services of the very client the PEP authenticates with, and the AuthZEN request maps onto them directly. The subject is a Keycloak user or client, the resource's type and ID are the type and name of a Keycloak resource, and the action is a scope. A resource that is not registered in Keycloak is simply denied. As of Keycloak 26.8.2, the latest release at the time of writing, it supports the Evaluation and Evaluations APIs, but not yet the Search APIs. It publishes metadata per realm, so discovery works with the realm URL as the PDP URL; the endpoints live below /realms/{realm}/authzen. The PEP authenticates with a token of a confidential client that has a service account and Authorization Services enabled. How Closely Keycloak Follows the Specification While building interop tests against Keycloak, I found a few places where it differs from the specification or loses a distinction the specification makes, and opened issues for them in the Keycloak project: Unknown fields are rejected. action.properties is optional in the specification, and receivers must ignore fields they do not know. Keycloak answers both with 400, also for unknown keys in options (keycloak/keycloak#54542).No challenge on 401. The specification says a 401 should carry a WWW-Authenticate header; Keycloak's AuthZEN endpoints send none (#54516, a fix is proposed in pull request #54517, awaiting review).Resource properties and context share one namespace. Both end up in the same attribute map, and a context entry silently overrides a resource property with the same name, so a policy cannot tell them apart (#54848). None of these block real use, and the feature is explicitly experimental. They are typical of what interop testing against a real PDP brings to light. authzen-enforcer: A PEP for Java Even with a standard API in place, every application still has to discover the PDP, authenticate to it, handle its failures, and deny when no decision arrives. An SDK takes this ceremony away and does it the same way everywhere, which carries the specification’s goal of standardization into the application itself. My own experience taught me how much such an SDK matters. In a previous role, I designed and built a Java PEP SDK with Keycloak Authorization Services as the PDP, and as a contributor to Keycloak, I have been following its AuthZEN support closely. My first plan was to help with the AuthZEN extension the Quarkus team had planned, but their work was already underway, and their review capacity was committed elsewhere. So instead of a Quarkus extension, I started a framework-independent Java SDK that any framework integration, Quarkus included, can build on. This is how authzen-enforcer came about. It is an open-source (Apache 2.0) Java SDK that plays the PEP role. It is published on Maven Central, and its interop tests run against Keycloak on every build. It is an independent project, not affiliated with the OpenID Foundation. Its design goals follow from the specification: Zero runtime dependencies in the core module. It runs on Java 17+ and uses only the JDK, including its own small JSON codec, so it never conflicts with your dependency tree.Minimal configuration. You give the PDP URL and a credential; endpoints come from discovery, with the metadata validated as the specification requires.Fail-closed by default. The client returns a decision only when the PDP gave one in a valid response. An unreachable PDP, a timeout, a 4xx/5xx or an invalid response throws an AuthZenException, which the application treats as a deny. The enforcer, which the Spring Boot starter builds on, turns every such failure into a deny itself. It lets requests through without a decision only if fail-open is enabled explicitly, and then only while the PDP is unavailable.The PEP authenticates as itself. The SDK never talks to an authorization server and never forwards the end user’s token. You supply the PEP’s credential through a CredentialProvider. At the time of writing, the latest release is 0.2.0, available on Maven Central. The core module, authzen-enforcer-core, covers the whole Authorization API, that is, the Access Evaluation and Access Evaluations APIs, the Subject, Resource and Action Search APIs with pagination, and discovery. Next to it are a Spring Boot starter, modules that publish the client's metrics to Micrometer and its traces to OpenTelemetry, and a BOM that keeps the versions of all modules aligned. Planned next are an adapter for Spring Security's OAuth 2.0 client, so that Spring obtains and refreshes the PEP's token, support for WebFlux, auto-configuration for metrics and health, DPoP-bound tokens towards the PDP, and a Quarkus extension. Spring Boot Support Out of the Box The role of frameworks in enterprise application development is clear, and an SDK that aims to be useful to the community cannot leave them out. Considering how widely Spring is used in the Java community, Spring Boot was the natural first target. The Spring Boot starter, a preview for Spring MVC on Spring Boot 4, enforces annotated handlers before they run, and the PDP’s base URL is the only setting it requires. To include the starter in your project, add the following dependency. XML <dependency> <groupId>io.github.authzenenforcer</groupId> <artifactId>authzen-enforcer-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency> The minimum configuration is the PDP’s base URL. With Keycloak as the PDP, this is the URL of the realm. YAML authzen: pdp: url: https://keycloak.example.com/realms/acme Keycloak also expects the PEP to authenticate, so the application defines a CredentialProvider bean that supplies the PEP's token. Auto-Inference With @CheckPermission For protecting endpoints, the starter offers a developer-friendly @CheckPermission annotation. Placed on a controller method, it asks the PDP before the method runs. It can also be placed on the controller class to cover all of its handler methods, in which case an annotation on a method takes precedence attribute by attribute. In either place, it does not have to spell out the AuthZEN request. Whatever the annotation leaves out, the starter infers from the request itself, and every inferred value can be overridden explicitly. The details are described in the @CheckPermission documentation. The following controller methods show typical usage scenarios, each annotated with the request it produces. Java @CheckPermission // read on {type: "documents", id: <id>} @GetMapping("/documents/{id}") Document get(@PathVariable String id) { ... } @CheckPermission // list on {type: "collection", id: "documents"} @GetMapping("/documents") List<Document> list() { ... } @CheckPermission(action = "cancel", resourceType = "order", resourceId = "#id") @PostMapping("/orders/{id}/cancel") void cancel(@PathVariable String id) { ... } Whatever the annotation does not say is inferred: The subject from the authenticated caller in Spring Security (the sub claim, with type user);The action from the HTTP method: GET is read on a single resource and list on a collection, POST is create, PUT/PATCH is update, DELETE is delete, and CORS preflight requests pass through without asking the PDP;The resource from the route pattern that Spring matched, never from the raw URI, so the way a client spells the path cannot change which resource the PDP is asked about. The inferred type is the route segment as it is, documents in the examples above, so it must match the resource type in Keycloak, or be mapped with authzen.enforcer.resource.type-names.documents: document. Every inferred part can be overridden on its own, in the annotation or in configuration. Routes that cannot be inferred safely, such as /{tenant}/documents, are denied without asking the PDP and reported as warnings at startup, so you find them before your users do. A collection is never sent as a "*" wildcard, which a PDP could read as "every resource". Expressions in the annotation can read path variables, selected request fields, and the caller's claims. Headers and parameters that carry standard credentials, such as Authorization, Cookie and access_token, read as null. A credential the application defines itself, such as a custom API key header, is not recognized, so keep such values out of the context. A deny becomes Spring Security’s AccessDeniedException, an anonymous caller its authentication entry point, so existing error handling keeps working. The PDP's reason stays on the server. Operating It A PEP that silently denies everything because its credential expired is a production incident waiting to happen. The SDK logs such failures as warnings with a rate limit and without leaking tokens or request values, and reports every call and enforcement to listeners. Optional modules publish them as Micrometer metrics and OpenTelemetry traces. A complete, runnable Spring Boot application with a Keycloak realm, along with a plain Java client, is available in the examples repository. How to Help I have learned a great deal from the Java community, and I try to give back through articles, tutorials, and talks at conferences, meetups, and webinars. I started this project in the same spirit, driven by the ideas shared in this article, so any kind of contribution is warmly welcome, whether it is code, documentation, testing against another PDP, or simply feedback. If you run a PDP other than Keycloak, the most valuable contributions are interop tests against it and a short page about its behavior; both are open as issues, along with a few good first issues. Questions and ideas are welcome in GitHub Discussions. Conclusion AuthZEN gives authorization what OpenID Connect gave authentication: a standard way for applications to ask their question. Its Authorization API, final since January 2026, reduces every access check to a subject, an action, a resource, and a context, answers it with a simple decision, and offers single, batch, and search requests along with discovery of the PDP’s endpoints. Close to twenty implementations have already taken part in its interop events, and Keycloak, the identity provider many Java teams already run, acts as an AuthZEN PDP today, even if its support is still experimental. With the standard in place, what remained was putting it into practice inside applications, and authzen-enforcer is an effort to do that for Java, with a zero-dependency, fail-closed core and a Spring Boot starter built around @CheckPermission. That is where a standard pays off, letting you write the enforcement once and choose the PDP freely.
The Problem in One Section A production AI agent is a process that reads data, calls tools, and writes things — at machine speed, along action sequences nobody enumerated in advance. When we put that process on Kubernetes, the instinct is to hand it a service account with broad permissions and move on. The result is a principal with standing access that nobody reviews and a blast radius nobody scoped. Least privilege for agents is not a philosophy. It is a set of mechanisms, and Kubernetes already ships most of them: short-lived audience-bound tokens, RBAC, admission-enforced pod security, and network policy. In this lab, those mechanisms are five concrete enforcement points: projected tokens, TokenReview verification, the broker allowlist, the publish budget, and NetworkPolicy. The missing piece in most deployments is not the primitive — it is the pattern that wires them together. This tutorial builds that pattern as a reference implementation you can run in about 30–45 minutes, then tests every control the way an adversary would probe it. Three things change when the workload is an agent instead of a controller. First, action sequences are non-deterministic: you can write an RBAC policy for a controller because it does the same thing every time, but an agent's next action depends on model output, tool results, and conversation state, so "allow exactly what it needs" is a moving target. Second, tools are the real attack surface: an agent with a dozen tools is a dozen small programs, and most teams authorize the agent once for all of them — read access to private data plus a publish-capable tool, combined by an actor that sees no reason not to, is the canonical failure shape. Third, identities outlive their tasks: tokens issued for a ten-minute job become standing access when the session never ends. I designed the lab below around exactly these three properties. Nothing here is a production system. I built it as a lab, and it is labeled honestly as one. The point is that each mechanism in it is real, each boundary is enforced, and each test has an expected result you can verify with your own eyes. What You Will Learn By the end of this tutorial, you will be able to: Issue short-lived, audience-bound projected service-account tokens for each agent identity instead of handing agents long-lived credentials.Verify presented tokens through the Kubernetes TokenReview API — letting the API server, not local JWT decoding, decide whether a token is real and correctly scoped.Separate read and write authority behind a trusted tool broker, so agents hold identity but no direct Kubernetes API permissions.Enforce an action budget that halts a runaway agent after a fixed number of mutations.Lock agent egress with NetworkPolicy so the only reachable destinations are DNS and the broker.Read the broker's JSON audit trail to see exactly what each identity attempted and what the sandbox allowed. What You Will Build Two agent pods, agent-reader and agent-writer, each carrying a short-lived projected token for its own identity. They get no Kubernetes API permissions at all. Their only capability is talking to a trusted tool-broker service — the single write path in the system. The broker verifies every presented token through the Kubernetes TokenReview API, authorizes the caller against an allowlist, enforces a per-identity publish budget, and writes only to one named ConfigMap. NetworkPolicy then shrinks the blast radius further: agents can reach the broker and DNS, and nothing else. ComponentIdentityCan doCannot doagent-reader podagent-reader SA, projected token (aud agent-tools, 1h)Read the internal note via the brokerPublish; touch the K8s API; reach the internetagent-writer podagent-writer SA, projected token (aud agent-tools, 1h)Publish via the broker (budget: 3)Read the note; touch the K8s API; reach the internettool-brokertool-broker SACreate TokenReviews; get/patch/update the agent-output ConfigMapEverything else Figure 1 — Architecture: two agent identities, one trusted broker, one writable object. Guardrail checklists and architecture essays describe this pattern; the tutorial below implements it end-to-end as runnable code you can break and re-run. Most hand-rolled agent identity schemes stumble on the same step — verifying the token. This implementation gets it right by design: the broker never parses the JWT itself, and the API server, through TokenReview, is the only party that can vouch for a token's validity, identity, and audience. The trust boundary is the broker. The broker never decodes or verifies the JWT itself — that is the classic mistake. Verifying a signature locally only tells you who signed the token; only the API server can tell you whether it is currently valid, issued to that identity, and scoped to your audience. Re-implementing any of that yourself is how confused-deputy holes are born. Prerequisites A Kubernetes cluster with a policy-enforcing CNI such as Calico or Cilium. This matters: kind's default CNI does not enforce NetworkPolicy, so the egress test will not fail there. minikube start --cni=calico is a known-good starting point. An existing cluster with Calico or Cilium works too.kubectl, and kustomize (or kubectl 1.14+, which embeds it).About 30–45 minutes. Python 3.12 container images are pulled from the public registry, so the cluster nodes need registry access. Step 1: The Namespace and the Two Identities Everything lives in agent-lab. The namespace carries the restricted Pod Security Standard on all three tracks — enforce, audit, warn — so any pod that does not meet the restricted profile is rejected outright: YAML apiVersion: v1 kind: Namespace metadata: name: agent-lab labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/audit-version: latest pod-security.kubernetes.io/warn: restricted pod-security.kubernetes.io/warn-version: latest The identities are plain ServiceAccounts with no roles attached. That is a deliberate choice: I made the projected tokens, not RBAC grants, the source of their authority. YAML apiVersion: v1 kind: ServiceAccount metadata: name: agent-reader namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: agent-writer namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: tool-broker namespace: agent-lab Step 2: Give the Broker — and Only the Broker — Scoped API Rights The broker needs exactly two capabilities from the Kubernetes API, and both are scoped to the minimum: create on tokenreviews (a ClusterRole, since TokenReview is cluster-scoped) so it can ask the API server to verify agent tokens.get/patch/update on the single named ConfigMap agent-output, so it can record publishes. The agent identities receive nothing: YAML apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: agent-lab-tokenreview rules: - apiGroups: ["authentication.k8s.io"] resources: ["tokenreviews"] verbs: ["create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: agent-lab-broker-tokenreview roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: agent-lab-tokenreview subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: agent-lab-output-writer namespace: agent-lab rules: - apiGroups: [""] resources: ["configmaps"] resourceNames: ["agent-output"] verbs: ["get", "patch", "update"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: agent-lab-broker-output-writer namespace: agent-lab roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: agent-lab-output-writer subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab Note the resourceNames restriction. A Role that allows patching "ConfigMaps" is a very different thing from a Role that allows patching the agent-output ConfigMap. Least privilege is always measured against the specific resource. Step 3: The Broker — TokenReview, Allowlist, Budget, Audit Log The broker is a stdlib-only Python service (no dependencies to audit, no framework to misconfigure). Read it carefully; every control in the lab is implemented here: Authentication: the presented bearer token is sent to POST /apis/authentication.k8s.io/v1/tokenreviews with spec.audiences: ["agent-tools"], using the broker pod's own in-cluster credentials. The broker then checks status.authenticatedand that status.audiences contains agent-tools — the TokenReview API docs call this out explicitly, because a token valid only against the API server's own audience would otherwise pass.Authorization: reader may GET /artifacts/internal-note; writer may POST /publish. The wrong pairing returns 403; a missing or bad token returns 401.Budget: three successful publishes per identity per broker process; the fourth returns 429. The counter is in memory on purpose — the code says so in a comment, and the production section below says what to use instead.Audit: one JSON line per request — timestamp, request id, username, action, status. The token is never logged. That rule matters more than it looks: the most common way identity systems leak is through their own logs.Inputs: JSON body only, 100 KiB cap, non-empty title/body strings with length limits. Python #!/usr/bin/env python3 """tool-broker -- the only write path for agent pods in agent-lab.""" import json import os import ssl import time import uuid import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, HTTPServer NAMESPACE = "agent-lab" EXPECTED_AUDIENCE = "agent-tools" READER = "system:serviceaccount:%s:agent-reader" % NAMESPACE WRITER = "system:serviceaccount:%s:agent-writer" % NAMESPACE NOTE_PATH = os.environ.get("NOTE_PATH", "/data/internal-note.txt") OUTPUT_NAME = os.environ.get("OUTPUT_CONFIGMAP", "agent-output") PUBLISH_BUDGET = 3 MAX_BODY_BYTES = 100 * 1024 LISTEN_PORT = int(os.environ.get("PORT", "8080")) SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount" def _k8s_request(method, path, body=None, content_type="application/json"): # Use the in-cluster DNS name so TLS hostname verification stays on. host = os.environ.get("KUBERNETES_SERVICE_DNS", "kubernetes.default.svc") port = os.environ.get("KUBERNETES_SERVICE_PORT", "443") with open(os.path.join(SA_DIR, "token"), "r", encoding="utf-8") as fh: sa_token = fh.read().strip() with open(os.path.join(SA_DIR, "ca.crt"), "rb") as fh: ca_data = fh.read() url = "https://%s:%s%s" % (host, port, path) data = json.dumps(body).encode("utf-8") if body is not None else None req = urllib.request.Request( url, data=data, method=method, headers={"Content-Type": content_type, "Authorization": "Bearer %s" % sa_token}) ctx = ssl.create_default_context(cadata=ca_data) # chain + hostname verified try: with urllib.request.urlopen(req, context=ctx, timeout=10) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: payload = exc.read().decode("utf-8", "replace") try: return exc.code, json.loads(payload) except ValueError: return exc.code, {"error": payload} def verify_token(token): review = { "apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview", "spec": {"token": token, "audiences": [EXPECTED_AUDIENCE]}, } status_code, payload = _k8s_request( "POST", "/apis/authentication.k8s.io/v1/tokenreviews", review) if status_code not in (200, 201, 202): return None status = payload.get("status", {}) if not status.get("authenticated"): return None if EXPECTED_AUDIENCE not in status.get("audiences", []): return None return status.get("user", {}).get("username") def record_publish(title, body): patch = {"data": {"lastTitle": title, "lastBody": body} status_code, _ = _k8s_request( "PATCH", "/api/v1/namespaces/%s/configmaps/%s" % (NAMESPACE, OUTPUT_NAME), patch, content_type="application/merge-patch+json", ) if status_code not in (200, 201, 202): raise RuntimeError("ConfigMap patch failed with status %s" % status_code) class BrokerHandler(BaseHTTPRequestHandler): server_version = "tool-broker/1.0" budgets = {} # in-memory on purpose; production needs durable state def log_message(self, *args): pass # silence default access logging def log_json(self, username, action, status, extra=None): record = { "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "rid": getattr(self, "rid", "-"), "username": username, "action": action, "status": status, } if extra: record.update(extra) print(json.dumps(record), flush=True) # the token is never logged def _respond(self, status, payload, username, action, extra=None): body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) self.log_json(username, action, status, extra) def _bearer_token(self): auth = self.headers.get("Authorization", "") scheme, _, value = auth.partition(" ") if scheme.lower() != "bearer" or not value: return None return value def _authenticate(self, action): token = self._bearer_token() if not token: self._respond(401, {"error": "missing bearer token"}, "anonymous", action) return None try: username = verify_token(token) except Exception as exc: self._respond(502, {"error": "identity verification unavailable"}, "anonymous", action, {"detail": str(exc)}) return None if not username: self._respond(401, {"error": "invalid or mis-scoped token"}, "anonymous", action) return None return username def do_GET(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "GET %s" % path username = self._authenticate(action) if not username: return if path == "/artifacts/internal-note": if username != READER: self._respond(403, {"error": "forbidden"}, username, action) return try: with open(NOTE_PATH, "r", encoding="utf-8") as fh: note = fh.read() except OSError as exc: self._respond(500, {"error": "note unavailable"}, username, action, {"detail": str(exc)}) return self._respond(200, {"note": note}, username, action) return self._respond(404, {"error": "not found"}, username, action) def do_POST(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "POST %s" % path username = self._authenticate(action) if not username: return if path != "/publish": self._respond(404, {"error": "not found"}, username, action) return if username != WRITER: self._respond(403, {"error": "forbidden"}, username, action) return length = self.headers.get("Content-Length") try: n = int(length) if length else 0 except ValueError: n = 0 if n > MAX_BODY_BYTES: self._respond(413, {"error": "body too large"}, username, action) return raw = self.rfile.read(n) if n else b"" try: payload = json.loads(raw.decode("utf-8")) if raw else {} except (UnicodeDecodeError, ValueError): self._respond(400, {"error": "body must be JSON"}, username, action) return title = payload.get("title") body = payload.get("body") if (not isinstance(title, str) or not isinstance(body, str) or not title or not body): self._respond(400, {"error": "need non-empty 'title' and 'body' " "strings"}, username, action) return if len(title) > 2000 or len(body) > 100000: self._respond(400, {"error": "title/body exceed length limits"}, username, action) return used = BrokerHandler.budgets.get(username, 0) if used >= PUBLISH_BUDGET: self._respond(429, {"error": "publish budget exhausted"}, username, action, {"used": used, "budget": PUBLISH_BUDGET}) return try: record_publish(title, body) except Exception as exc: self._respond(500, {"error": "publish failed"}, username, action, {"detail": str(exc)}) return BrokerHandler.budgets[username] = used + 1 self._respond(202, {"published": True, "budget_used": used + 1, "budget": PUBLISH_BUDGET}, username, action, {"title": title}) def main(): server = HTTPServer(("0.0.0.0", LISTEN_PORT), BrokerHandler) print(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "event": "broker listening", "port": LISTEN_PORT}), flush=True) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main() The broker runs as a Deployment with its code and the internal note mounted from ConfigMaps (read-only), a ClusterIP Service on port 8080, and the same restricted hardening as everything else in this lab. Its own service account token is automounted — the broker is a trusted first-party component and needs its identity to call the API server. The demo data the broker serves is fictional, and it says so in the file itself: YAML apiVersion: v1 kind: ConfigMap metadata: name: internal-note namespace: agent-lab data: internal-note.txt: | DEMO CONTENT — this note is fictional and exists only for the lab. ... Step 4: The Agent Pods — Projected Tokens, Nothing Else Each agent pod gets exactly one credential: a projected ServiceAccount token with audience: agent-tools and a one-hour lifetime, mounted at /var/run/secrets/agent/token. The in-cluster token is not automounted (automountServiceAccountToken: false), which is the whole point — kubectl auth can-i will confirm these identities cannot touch the API at all. YAML spec: serviceAccountName: agent-reader automountServiceAccountToken: false ... volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token Every container in the lab — broker and agents — runs with the same restricted-compatible profile: non-root user, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, all capabilities dropped, read-only root filesystem, PYTHONDONTWRITEBYTECODE=1 so the interpreter never tries to write .pyc files. A tiny caller.py (stdlib only) rides along in each agent pod via a ConfigMap. It reads the projected token fresh from disk on every call — projected tokens rotate, so caching them is a bug — and performs the requested action against the broker: Python def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() # fresh read every call req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) ... # usage inside the pod: # python3 /app/caller.py read # python3 /app/caller.py publish "demo title" "demo body" Step 5: Shrink the Network Blast Radius Identity controls what an agent may ask for. NetworkPolicy controls what it can reach. Agents accept no inbound traffic at all and may only talk to the broker on port 8080, plus DNS in kube-system: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: agent-default-deny namespace: agent-lab spec: podSelector: matchLabels: agent-lab/component: agent policyTypes: [Ingress, Egress] ingress: [] # deny all inbound traffic to agent pods egress: - to: - podSelector: matchLabels: app: tool-broker ports: - protocol: TCP port: 8080 - to: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: kube-system podSelector: {} ports: - protocol: UDP port: 53 - protocol: TCP port: 53 A second policy locks the broker's ingress to agent pods on port 8080. This is the control that turns "the agent decided to exfiltrate" into "the connection timed out." Step 6: Run the Tests How this was verified. No live cluster was used during writing: the broker's authorization and budget logic was checked with an automated test suite that stubs the TokenReview call and the ConfigMap patch: missing token → 401, bad token → 401, reader read → 200, reader publish → 403, writer read → 403, three publishes → 202 each, fourth publish → 429, with exactly three patches recorded (10/10 checks passed). The cluster steps below are your live run of that same matrix; this tutorial does not claim an observed live-cluster execution. Deploy everything with kustomize, which generates the ConfigMaps from the Python files: Shell cd agent-security-lab kubectl apply -k . kubectl rollout status deploy/tool-broker -n agent-lab kubectl get pods -n agent-lab Now probe the sandbox the way an adversary — or a confused agent — would. 1. The reader can read (expect 200): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py read HTTP HTTP 200 {"note": "DEMO CONTENT — this note is fictional and exists only for the lab.\n..."} 2. The reader cannot publish (expect 403): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py publish "x" "y" HTTP HTTP 403 {"error": "forbidden"} 3. The writer cannot read (expect 403): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py read HTTP HTTP 403 {"error": "forbidden"} 4. The writer can publish — three times — and the ConfigMap shows it: Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-1" "first write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-2" "second write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-3" "third write" kubectl get configmap agent-output -n agent-lab -o jsonpath='{.data.lastTitle}{"\n"}{.data.lastBody}{"\n"}' HTTP HTTP 202 {"published": true, "budget_used": 1, "budget": 3} HTTP 202 {"published": true, "budget_used": 2, "budget": 3} HTTP 202 {"published": true, "budget_used": 3, "budget": 3} demo-3 third write 5. The fourth publish is refused (expect 429): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-4" "over budget" HTTP HTTP 429 {"error": "publish budget exhausted", "used": 3, "budget": 3} This is the containment control working as designed: a runaway agent gets exactly three mutations and then stops, no matter what it believes it should do next. 6. The agent identities have no Kubernetes API access: Shell kubectl auth can-i get secrets --as=system:serviceaccount:agent-lab:agent-reader -n agent-lab kubectl auth can-i get configmaps --as=system:serviceaccount:agent-lab:agent-writer -n agent-lab Plain Text no no 7. Every request leaves one audit line, and tokens never appear in logs: Shell kubectl logs -n agent-lab deploy/tool-broker | tail -4 JSON ... {"ts": "2026-10-14T19:40:02Z", "rid": "a3f19c2d81be", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 202, "title": "demo-3"} {"ts": "2026-10-14T19:40:11Z", "rid": "2c1e4b9f30d2", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 429, "used": 3, "budget": 3} 8. External egress fails on a policy-enforcing CNI (CNI-dependent test): Shell kubectl exec -n agent-lab agent-reader -- timeout 8 python3 -c \ "import socket; socket.create_connection(('1.1.1.1', 443), timeout=5)" Python Traceback (most recent call last): ... TimeoutError: timed out On kind's default CNI, this test will succeed — that is the prerequisite warning, not a lab bug. The policy is applied correctly; kindnetd simply does not enforce it. Cleanup: Shell kubectl delete namespace agent-lab The broker's decision path, drawn from broker.py, is worth keeping in front of you while you read the tests above — every request walks the same corridor, and every rejection is a gate with a code: Figure 2 — The broker's decision path for every request. Troubleshooting External-egress test still succeeds. Symptom: test 8 reaches 1.1.1.1:443 instead of timing out. Cause: the cluster's CNI does not enforce NetworkPolicy — kind's default CNI (kindnetd) installs the policy objects but never applies them. Fix: run the lab on a policy-enforcing CNI such as Calico or Cilium; minikube start --cni=calico is a known-good starting point. Every broker call returns 401 or 502. Symptom: the caller gets {"error": "invalid or mis-scoped token"}, or the broker answers 502 identity verification unavailable. Cause: the broker cannot reach the TokenReview endpoint, or the presented token is not meant for this service. Fix: check kubectl logs -n agent-lab deploy/tool-broker for the underlying error; confirm the ClusterRoleBinding grants the broker's ServiceAccount create on tokenreviews; and confirm the projected volume's audience is exactly agent-tools in both agent pod specs. Agent pods stuck Pending or rejected at admission. Symptom: kubectl get pods -n agent-lab shows Pending, or kubectl describe pod reports a forbidden admission error. Cause: the agent-lab namespace enforces the restricted Pod Security Standard, and any pod that violates it is rejected. Fix: confirm each pod's securityContext sets runAsNonRoot: true, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, and capabilities.drop: ["ALL"] — the manifests in this lab already do. Publish returns 500. Symptom: {"error": "publish failed"} on a POST the allowlist should permit. Cause: the broker's own Role does not actually permit the write. Fix: confirm the agent-lab-output-writer RoleBinding exists in agent-lab and its resourceNames contains exactly agent-output; the broker patches one named ConfigMap and nothing else, so a renamed or missing ConfigMap fails closed. Taking This to Production: What the Lab Deliberately Leaves Out The lab's budget counter lives in broker memory; a restart resets it. Production budgets must be durable — etcd, Redis, or a database with atomic increments — and scoped per task, not per process. The audit lines go to stdout; production ships them to a tamper-evident store the agent cannot reach, with alerts on the 429s and 403s, not just retention. Three more things a real deployment adds. First, admission policy: the pattern in this lab should be enforced, not suggested. A policy engine such as Kyverno or OPA Gatekeeper can require automountServiceAccountToken: false, projected tokens with a sane expirationSeconds, and the restricted security context on every agent pod — so the sandbox is the default, not an option somebody remembers to apply. Second, per-task pods: long-lived agent identities accumulate authority. Minting a fresh pod and identity per task, with the token expiring with the task, bounds every session the way the lab bounds every publish. Third, human approval for high-risk actions: the broker's allowlist is static here. In production, the dangerous subset of tools — anything that writes, deletes, or crosses a trust boundary — sits behind an approval step or a policy check, not just an allowlist entry. And one response mechanism the lab does not demonstrate, but every deployment needs: a kill switch with quarantine-first semantics. When monitoring flags anomalous agent behavior — unusual data access patterns, write volume spikes, calls to unexpected destinations — the response should be automatic containment: revoke the session tokens, freeze the write identity, preserve the audit trail. You can always re-issue access after review; you cannot un-publish what a runaway agent already sent. The budget 429s and the 403s in the broker logs are the signals this switch consumes. And the internal note's stand-in for a secret store should be exactly that: a secret store with dynamic, short-lived credentials, never a ConfigMap. Trade-Offs, Stated Plainly This pattern is friction, and friction has a price. Per-agent projected tokens mean token plumbing everywhere a caller touches. A broker in front of every tool is a new service to operate, scale, and secure — and it becomes the most attractive target in the system, which is why its own RBAC is the tightest in the lab. Budgets turn "the agent did something wrong a thousand times" into "it did it three times and stopped," but they also turn a legitimate long task into a 429 that needs a human to raise the ceiling. Default-deny egress breaks the first integration that assumed the open internet, and the person who allowlists the fix had better write down why. The alternative is standing access for non-deterministic actors, reviewed never and rotated never, with no containment when the run goes sideways. That is not a trade-off; that is the absence of one. The mechanisms in this lab — verified identity, separated authorities, budgets, egress that defaults to no, audit trails that assume the actor will surprise you — are the price of running agents in production. Pay it deliberately, or pay it later in incident reviews. Conclusion Agents are principals now, but Kubernetes still provisions most of them like interns on their first day: broad access, issued once, reviewed never. This lab shows the other shape — short-lived audience-bound identity verified through TokenReview, a trusted broker as the only write path, allow-listed tools, action budgets, and a network that defaults to no — as running code you can test in about 30–45 minutes. None of these mechanisms is new. What the lab adds is their composition in one request path — TokenReview, then allowlist, then budget, then a single named write, then an audit line — applied to the workloads that need it most. The complete lab — every manifest, the kustomize setup, and both Python files — is printed in full in this article and its appendix, so you can reproduce it exactly; only the stubbed broker unit tests live outside it, and their results are quoted in Step 6. Run it, break it, and then decide which controls your agents are missing. References ServiceAccount token volume projection – projected tokens, audiences, and expirationSecondsTokenReview API reference – authentication.k8s.io/v1 request/response shapes and audience validationNetworkPolicy – ingress/egress rules and the policy-enforcing CNI requirementPod Security Standards – the restricted profile enforced on the lab namespace Appendix: The Remaining Manifests The walkthrough above prints the namespace, the service accounts, the RBAC, the demo data ConfigMap, the agent NetworkPolicy, and the broker code in full. The rest of the lab — the pieces the steps describe but do not print — is reproduced here, copied verbatim, so the article is self-contained. The broker's Deployment and Service: YAML # The tool-broker is the only write path in the lab. It is a trusted # first-party component: its own service account token is automounted so it # can call the TokenReview API and patch the single "agent-output" # ConfigMap -- nothing else. apiVersion: apps/v1 kind: Deployment metadata: name: tool-broker namespace: agent-lab spec: replicas: 1 selector: matchLabels: app: tool-broker template: metadata: labels: app: tool-broker spec: serviceAccountName: tool-broker securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: broker image: python:3.12-alpine command: ["python3", "/app/broker.py"] ports: - name: http containerPort: 8080 env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: NOTE_PATH value: /data/internal-note.txt volumeMounts: - name: code mountPath: /app readOnly: true - name: note mountPath: /data readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: code configMap: name: broker-code items: - key: broker.py path: broker.py defaultMode: 0444 - name: note configMap: name: internal-note items: - key: internal-note.txt path: internal-note.txt defaultMode: 0444 --- apiVersion: v1 kind: Service metadata: name: tool-broker namespace: agent-lab spec: type: ClusterIP selector: app: tool-broker ports: - name: http port: 8080 targetPort: 8080 The two agent pods in full: YAML # Two agent pods. Each carries a short-lived, audience-bound projected # token (audience "agent-tools", 1 hour) for its own identity, mounted at # /var/run/secrets/agent/token. The in-cluster service account token is # NOT automounted, so the pods cannot talk to the Kubernetes API at all. apiVersion: v1 kind: Pod metadata: name: agent-reader namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: reader spec: serviceAccountName: agent-reader automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: reader - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 --- apiVersion: v1 kind: Pod metadata: name: agent-writer namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: writer spec: serviceAccountName: agent-writer automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: writer - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 The broker-side NetworkPolicy, which locks the broker's ingress to agent pods on port 8080: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: broker-ingress namespace: agent-lab spec: podSelector: matchLabels: app: tool-broker policyTypes: [Ingress] ingress: - from: - podSelector: matchLabels: agent-lab/component: agent ports: - protocol: TCP port: 8080 The kustomize entry point: YAML apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization namespace: agent-lab resources: - manifests/namespace.yaml - manifests/serviceaccounts.yaml - manifests/rbac.yaml - manifests/data-configmaps.yaml - manifests/broker.yaml - manifests/agents.yaml - manifests/networkpolicy.yaml configMapGenerator: - name: broker-code files: - code/broker.py - name: caller-code files: - code/caller.py generatorOptions: disableNameSuffixHash: true The full caller.py: Python #!/usr/bin/env python3 """caller -- runs inside the agent pods to exercise the tool-broker. Reads the projected ServiceAccount token fresh from disk on every call. Projected tokens are rotated by the kubelet, so the token is deliberately never cached. The token is presented in an Authorization header and never printed. """ import json import os import sys import urllib.error import urllib.request TOKEN_PATH = os.environ.get("AGENT_TOKEN_PATH", "/var/run/secrets/agent/token") BROKER_URL = os.environ.get("BROKER_URL", "http://tool-broker:8080") def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() data = json.dumps(payload).encode("utf-8") if payload is not None else None req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status, resp.read().decode("utf-8") except urllib.error.HTTPError as exc: return exc.code, exc.read().decode("utf-8", "replace") def main(argv): if len(argv) < 2 or argv[1] not in ("read", "publish"): print("usage: caller.py read | caller.py publish <title> <body>", file=sys.stderr) return 2 if argv[1] == "read": status, body = _call("GET", "/artifacts/internal-note") else: if len(argv) != 4: print("usage: caller.py publish <title> <body>", file=sys.stderr) return 2 status, body = _call("POST", "/publish", {"title": argv[2], "body": argv[3]}) print("HTTP %s" % status) print(body) return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) With these files, kubectl apply -k . from the lab directory deploys the complete sandbox exactly as tested in Step 6.
Building agents teaches you a humbling lesson very quickly: a well-written prompt is not the same as a guaranteed workflow. In production, agents occasionally behave in ways that are technically reasonable, yet operationally unexpected. This article shares one such observation and why offline evaluations became critical for catching it. The Assumption Most Agent Builders Make When we design an agent workflow, we naturally think like software engineers. If we define a sequence such as: Plain Text 1. Call Tool A 2. Validate the parameters 3. Call Tool B we expect execution to follow that exact order every time. After all, that's how traditional software behaves. If the workflow is clearly defined, the system should execute it deterministically. But agents are not workflow engines. And that distinction matters more than most teams realize. The Behavior We Observed Most executions followed the same sequence as mentioned above. However, a small percentage of executions behaved differently Plain Text 1. Validation 2. Tool A 3. Tool B The instructions remained unchanged. The tools remained unchanged. The input remained unchanged. Yet so often, the agent reordered the workflow. The deviation wasn't catastrophic, but it was enough to raise an important question: Why would an agent ignore a clearly defined sequence? A Common Misconception About Agents One of the biggest misconceptions in agent development is treating prompts as equivalent to program logic. Traditional software executes instructions. LLMs interpret instructions. That difference is subtle but significant. An agent's behavior emerges from several competing influences: System instructionsUser instructionsAvailable toolsContext provided in the sessionTraining dataLearned reasoning patterns As engineers, we often focus on the first three. The model, however, is also influenced by the latter three. Why This Happens One possible explanation is that validation and reasoning are deeply represented patterns in model training. Across countless examples, models learn behaviors such as: Plain Text 1. Understand first 2. Validate 3. Act As a result, when a workflow asks the model to perform an action before validation, there may occasionally be tension between "What the prompt says" and "What the model has learned to do." Sometimes, the model's learned reasoning pattern leaks through. The result is not necessarily a "failure" in the traditional sense. It's a reminder that agents are probabilistic systems. The Hidden Risk of Rare Failures Interestingly, the biggest risk isn't complete failure. It's intermittent failure. Consider two scenarios: Workflow fails 100% of the time. This problem is discovered immediately. Developers spot it within minutes.Workflow fails 5% of the time. The issue becomes harder to detect. Manual testing might never uncover it. The first indication may be too late, coming from production. Many agent-related issues fall into this category: Tool ordering issuesIncorrect tool selectionMissing validation stepsHallucinated assumptionsUnexpected reasoning paths These problems are often rare enough to evade traditional testing practices. Why Offline Evaluations Matter Prompts define intent. Evaluations verify behavior. Without systematic evaluations, agent testing often becomes anecdotal: "I tested it 15 times, and it worked!" The problem is that ten samples may not expose a behavior that occurs once every hundred executions. Offline evaluations provide a structured way to discover such patterns. A useful evaluation suite can measure: Instruction adherenceTool orderingWorkflow completionCorrectnessHallucination ratesSafety complianceLatencyRetry behavior For example: Plain Text Test Case: Expected: Tool A → Validation → Tool B Observed: Validation → Tool A → Tool B Result: Fail What appears to be a random anomaly often turns out to be a measurable behavioral tendency. What We Learned One mindset shift proved particularly valuable: Stop Treating Prompts as Guarantees Prompts are specifications. They are not enforcement mechanisms. As workflows become more critical, relying exclusively on prompt compliance becomes increasingly risky. Start Treating Evaluations as First-Class Engineering Artifacts Many teams invest heavily in prompt engineering while postponing evaluation design. In practice, both should evolve together. The earlier evaluation datasets are introduced, the easier it becomes to identify behavioral drift and instruction-following issues. Design Patterns That Reduce Workflow Deviations Over time, we found several design approaches that improve reliability. 1. Move Critical Orchestration Outside the LLM If execution order is non-negotiable, enforce it through application logic. Instead of: Plain Text LLM decides the next step prefer: Plain Text Application controls the workflow LLM performs bounded tasks 2. Introduce Explicit Workflow State Maintain state such as: Plain Text TOOL_A_COMPLETED VALIDATION_COMPLETED READY_FOR_TOOL_B This reduces ambiguity and limits the agent's ability to skip ahead. 3. Gate Tool Availability Only expose tools that are valid for the current stage. If Tool B should never execute before validation, don't make Tool B available until validation is complete. 4. Build Evaluation Suites Early Evaluation datasets should be created alongside agent workflows, not after deployment. This practice helps uncover edge cases before users encounter them. 5. Design for Probability, Not Perfection Perhaps the most important lesson: Reliable agent systems assume occasional deviations and are engineered to handle them gracefully. Systems designed around perfect compliance tend to be fragile. Systems designed around probable compliance tend to be resilient. Final Thoughts One of the most surprising discoveries in agent development is that a correct prompt does not necessarily produce a perfectly consistent workflow. Agents are capable, adaptable, and increasingly powerful. But they are not deterministic workflow engines. The observation that inspired this article was simple: an agent occasionally performed validation before executing a tool call despite being explicitly instructed not to. The lesson, however, was much larger. As we investigated further through offline evaluations, we realized that output correctness alone was not enough. The agent could arrive at the right answer while still deviating from the expected execution path, calling tools in an unexpected sequence, or violating workflow assumptions that were invisible to the end user. Those behaviors would have been easy to miss through manual testing alone. By monitoring tool invocations, execution order, tool call counts, and workflow compliance, offline evaluations helped surface issues that would otherwise have remained hidden until production. As teams move from experimenting with agents to deploying them in production, success will depend less on writing better prompts and more on building robust evaluation frameworks, orchestration mechanisms, and safeguards around inherently probabilistic systems. Because in the world of agents, the real challenge isn't getting the workflow right once. It's getting it right consistently, predictably, and observably. And that starts with measuring not just what the agent produces, but how it gets there.
If you've ever reached for SQLite to answer a question about a CSV, you already know the appeal: no server, one file, connect() and go. Relate (formerly CypherLite), a Neo4j project, brings that experience to graph data. It's an embedded graph database written in Rust, queried in Cypher, and runs inside your Python process. This article uses it in a notebook on a dataset that is naturally a graph, the London Underground. We'll load stations and connections, ask questions that would need self-joins in SQL, such as: What's within three stops?Which stations are interchanges?How do I get from A to B? and hand the results to pandas. The SQLite parallels are close. The database is a single .cl file or lives in memory. The Python API is connect() and execute() with named parameters, and rows come back keyed by column name. There is no daemon to start and no connection string. The full source code is available on GitHub. Install And Run A First Query The package is called relate-db on PyPI and imported as relate. Relate ships prebuilt wheels for Windows, Linux, and macOS, so there's nothing to compile. It needs Python 3.9 or later; the pinned package versions in the accompanying notebook need Python 3.11 or later. If you've used sqlite3, the first query will look familiar: Python db = relate.connect(":memory:") # or a path such as "tube.cl" db.execute("CREATE (:Station {name: $name})", {"name": "Kennington"}) for row in db.execute("MATCH (s:Station) RETURN s.name AS name"): print(row["name"]) execute() takes the query and a dictionary of parameters, and each row is addressable by column name. Use parameters rather than string formatting, for the same reason you would in SQL. Load The London Underground Data The dataset is three CSV files: Stations with coordinatesConnections between neighboring stations with the line that serves themA list of lines The connections file also holds other London rail lines, so the code keeps only the lines in the lines file. We'll read the files with pandas and pass the rows as a parameter. UNWIND turns the list into one row per record, similar to executemany in SQLite. Python stations = pd.read_csv("data/london_stations.csv") links = pd.read_csv("data/london_connections.csv") lines = pd.read_csv("data/london_lines.csv") for frame in (stations, links, lines): frame.columns = frame.columns.str.strip() # Keep the lines in the lines file, and only the stations those lines touch. links = links[links["Tube Line"].str.strip().isin(set(lines["Tube Line"].str.strip()))] used = set(links["From Station"].str.strip()) | set(links["To Station"].str.strip()) stations = stations[stations["Station"].str.strip().isin(used)] db = relate.connect("tube.cl") db.execute( "UNWIND $rows AS r " "MERGE (s:Station {name: r.name}) " "SET s.lat = r.lat, s.lon = r.lon", {"rows": [ {"name": str(r["Station"]).strip(), "lat": float(r["Latitude"]), "lon": float(r["Longitude"])} for r in stations.to_dict("records") ]}, ) db.execute( "UNWIND $rows AS r " "MATCH (a:Station {name: r.a}), (b:Station {name: r.b}) " "CREATE (a)-[:CONNECTS_TO {line: r.line}]->(b)", {"rows": [ {"a": str(r["From Station"]).strip(), "b": str(r["To Station"]).strip(), "line": str(r["Tube Line"]).strip()} for r in links.to_dict("records") ]}, ) Each connection is stored once. The queries below match it in either direction, so a trip works both ways without storing every link twice. Cypher also has LOAD CSV, which skips pandas. Relate denies local file reads unless we allow a directory explicitly, so the parameter route is the simpler approach in a notebook. We'll check the load with a count: Python print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) print(db.execute("MATCH ()-[r:CONNECTS_TO]->() RETURN count(r) AS links").data()) On the Underground data, this outputs 349 stations and 458 connections. Ask Graph Questions Three questions that need self-joins in SQL read as one pattern in Cypher. 1. What's Within Three Stops Of Kennington? A variable-length pattern follows connections up to a limit, in either direction: Python nearby = db.execute( "MATCH p = (a:Station {name: $name})-[:CONNECTS_TO*1..3]-(b:Station) " "WHERE a <> b " "RETURN b.name AS station, min(length(p)) AS stops " "ORDER BY stops, station", {"name": "Kennington"}, ).data() Kennington has 4 neighbors, 8 more stations two stops away and 12 more at three stops, 24 in all. 2. Which Stations Are Interchanges? Group each station's connections by line and keep the ones served by more than one: Python hubs = db.execute( "MATCH (s:Station)-[r:CONNECTS_TO]-() " "WITH s, collect(DISTINCT r.line) AS lines " "WHERE size(lines) > 1 " "RETURN s.name AS station, size(lines) AS lines, lines AS served_by " "ORDER BY lines DESC, station LIMIT 10" ).data() Kings Cross St. Pancras comes first with 6 lines, followed by Baker Street with 5. 3. How Do I Get From Kennington To Euston? Cypher 25 path selectors ask for the shortest paths directly. Two details matter: Bound the search with a hop limit, because an open-ended pattern makes the engine consider every path through a network full of loops.Name the line if you want one, as below. Python ORIGIN, DEST, LINE = "Kennington", "Euston", "Northern" MAX_HOPS = 10 # the shortest route is 8 hops; the bound keeps the search small found = db.execute( f"MATCH p = SHORTEST 3 (a:Station {{name: $origin})-[:CONNECTS_TO {{line: $line}]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, length(p) AS stops ORDER BY stops", {"origin": ORIGIN, "dest": DEST, "line": LINE}, ).data() # Keep each station sequence once. routes = list({tuple(r["stations"]): r for r in found}.values()) On the Northern Line, the query returns the two branches in a few milliseconds: Charing Cross (8 stops, via Waterloo and Embankment)Bank (9 stops, via Elephant and Castle and Angel) Where several lines serve the same stations, the graph holds parallel connections, and each counts as a separate path, so the same station sequence can come back more than once. We'll keep each sequence once. Drop the line filter and the same question runs across the whole network. We ask for more paths than we need, keep the distinct station sequences, and return the line on each hop, so we can see where the route changes: Python whole = db.execute( f"MATCH p = SHORTEST 20 (a:Station {{name: $origin})-[:CONNECTS_TO]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, [r IN relationships(p) | r.line] AS lines, length(p) AS stops " "ORDER BY stops", {"origin": ORIGIN, "dest": DEST}, ).data() distinct = list({tuple(r["stations"]): r for r in whole}.values()) This takes under a second and returns 20 paths, but only two distinct routes, because most paths differ only in which parallel connection they use. The shortest has 6 stops: Northern Line to Waterloo, Jubilee Line to Green Park, then the Victoria Line through Oxford Circus and Warren Street to Euston, with two interchanges. The other has 7 stops through Bank, Moorgate and Farringdon, using the Northern, Waterloo and City, and Circle or Metropolitan Lines. Fewer stops does not mean a better trip, which is why a route's interchanges belong in the comparison. In SQL, the same three questions require recursive CTEs or repeated self-joins. Move Results Into Pandas Every query above returns a list of dictionaries through .data(), which pandas takes directly: Python hubs_df = pd.DataFrame(hubs) hubs_df.plot.barh(x="station", y="lines", legend=False).invert_yaxis() For larger results, the native Database class can return Arrow IPC bytes, which avoids building Python objects row by row. It needs the file to be free, so we'll close the earlier connection first: Python db.close() # the file must be free for the native class adb = Database("tube.cl") buf = adb.execute_arrow("MATCH (s:Station) RETURN s.name AS name, s.lat AS lat, s.lon AS lon") stations_df = pa.ipc.open_stream(buf).read_all().to_pandas() adb.close() From here, the data is an ordinary DataFrame. We can plot it, merge it with other tables, or feed it to a model, and write findings back with a parameterized UNWIND when we want them in the graph. Keep It In One File A path ending in .cl stores the write-ahead log, the snapshots and the catalog in a single file, so the whole graph can be copied, emailed or committed alongside the notebook. A plain directory path works too, and ":memory:" gives us a throwaway database that disappears when the process ends. Python db.close() db = relate.connect("tube.cl") # the graph is still there print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) Close a connection before another one opens the same file. Relate allows one writer, and a second opener of a locked database gets an error (an OperationalError, "storage locked"), as it would in SQLite. By default, a write is acknowledged after it reaches the log, so a crash does not lose it. Summary Relate fits analysis on a graph that lives on a local machine: a notebook, a script, a unit test for a Cypher query, or a prototype before being moved to a server. Because the dialect is Cypher, the queries carry over to Neo4j. Know the limits before you build on it: The working set must fit in RAMIt's an engine, not a platform: it has no equivalent of Neo4j's plugin ecosystem, such as Graph Data Science, and it does not let you register your own Cypher functionsIt's a subset of what Neo4j runs, so check each feature you depend on against the documentation, and test your queries on both engines before choosing For many applications, these trade-offs will be fine. We get a graph, a query language, and a DataFrame in one pip install, with nothing to run in the background. In the next article, we'll see how to use Relate with TypeSafe AI's Jev, LLMs and MCP. We'll build an AI agent that navigates the London Underground while recording its decisions, alternatives, model judgments, and human interventions in a persistent, queryable graph ledger. Stay tuned! The full source code is available on GitHub.
Retries usually make systems more reliable. A dependency times out, processing pauses, and the message returns later. Eventually, the operation succeeds. That successful retry can also corrupt a projection. Consider a consumer maintaining product data. Version 108 of product P17 starts processing but encounters an enrichment timeout. Version 109 arrives seconds later and reaches the database successfully. Five minutes afterward, version 108 returns through the retry queue and overwrites it. Both events are legitimate. Neither is a duplicate. The database accepts valid SQL, and the consumer reports success. Yet the stored state has moved backward. The missing guarantee is freshness. An idempotent consumer can prevent repeated execution of one operation while still allowing an older operation to replace newer state. Why Deduplication Cannot Catch This Suppose each product update carries a unique event identifier: Plain Text eventId=A, productId=P17, sourceVersion=108 eventId=B, productId=P17, sourceVersion=109 An idempotency check correctly treats these as different operations. Assuming failed attempts do not mark events complete, event A remains eligible for processing after its enrichment failure. Nothing about its identity tells the consumer that version 109 has already superseded it. Two separate questions must therefore be answered: Idempotency: Has this operation already been applied?Freshness: May this operation replace the state currently stored? For a projection governed by an authoritative revision, the required invariant is straightforward: the persisted version must never decrease. A replay can leave it unchanged, and a newer update can advance it. Event identifiers and source revisions serve different purposes. Preserving both avoids forcing one mechanism to provide a guarantee it cannot express. Reproduce the Failure at the Database Boundary The failure does not require a message broker. Two writes arriving in the wrong order are sufficient. Start with a small PostgreSQL table: SQL CREATE TABLE product_view ( product_id VARCHAR(64) PRIMARY KEY, source_version BIGINT NOT NULL, payload JSONB NOT NULL ); A conventional upsert accepts whichever update arrives last: SQL INSERT INTO product_view (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload; If version 109 already exists, this statement replaces it with version 108. The database has followed the instruction exactly. The application never expressed a freshness constraint. This distinction matters during incident analysis. A retry queue explains why an event arrived late. The unconditional write explains why late arrival damaged state. Why Locks and Application Checks Fall Short A lock alone does not establish freshness. Version 109 can acquire the lock, write successfully, and release it. Version 108 can acquire that same lock later and overwrite the row. Processing was perfectly serialized, but the order was wrong. An application-level comparison introduces a different problem: Java Product current = repository.find(productId); if (incoming.version() > current.version()) { repository.save(incoming); } Starting from version 107, workers carrying 108 and 109 can both read the same row. Both comparisons pass. If the worker carrying 108 writes last, the projection regresses. The issue is the gap between comparison and mutation. A lock covering both operations can protect this sequence when implemented correctly, but the freshness comparison remains essential. For a single-row projection, putting the condition directly in the write makes the invariant explicit. Make the Write Enforce Freshness Add a version predicate to the conflict-update branch: SQL INSERT INTO product_view AS stored (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload WHERE stored.source_version < EXCLUDED.source_version RETURNING product_id, source_version; PostgreSQL evaluates the conflict-update condition against the conflicting row. Rows excluded by that condition are not returned by RETURNING. See the PostgreSQL INSERT documentation. If 108 commits first, 109 can advance the row. If 109 commits first, 108 cannot replace it. Equal versions also leave the row unchanged. The comparison now occurs within the database operation that controls mutation. Concurrent processing no longer depends on the newest event finishing last. Transactions can still encounter deadlocks or serialization failures, depending on the workload and isolation level. Those failures require appropriate transaction retries; the version predicate must remain part of every attempt. PostgreSQL documents these distinctions in its transaction isolation guidance. Establish What the Version Actually Means The predicate is useful only when larger revisions represent newer authoritative state for the same entity. A source-owned aggregate revision is a strong candidate. A datastore revision or producer sequence can also work when its ordering contract is explicit. Random UUIDs establish identity without establishing order. Wall-clock timestamps require careful guarantees around clock synchronization, precision, and concurrent writers. Offsets from unrelated partitions do not provide a shared entity ordering. The payload must also correspond to its claimed revision. If enrichment reads changing external data, retrying version 109 might produce a different payload from the first attempt. The fence prevents replacement, but the inconsistency remains worth investigating. Define whether each event carries a complete snapshot or a dependent delta. Skipping revision 108 is safe only when 109 contains everything needed to represent the newer state. A sequence of incremental adjustments may require ordered processing or gap recovery. Distinguish Stale Updates From Conflicting Replays A rejected write has several possible meanings: incomig updateinterpretation Lower revision Stale delivery Equal revision, identical payload Replay Equal revision, different payload Consistency violation Higher revision Eligible replacement The SQL predicate protects the row but does not distinguish all these outcomes. If exact classification matters, compare against the protected row within a suitable transaction or retain revision-specific payload hashes. A later, unprotected read can observe a further update and obscure what happened during the original decision. Same-version conflicts can reveal nondeterministic enrichment, incorrect revision assignment, or corrupted replay data. Treating them as ordinary duplicates hides a broken data contract. Preserve Versions Across Deletion Physical deletion creates another opening for stale retries. Suppose version 121 deletes P17. If the row disappears entirely, a delayed version 120 encounters no conflict and inserts the product again. Preserve the deletion revision with a tombstone: SQL ALTER TABLE product_view ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE, ALTER COLUMN payload DROP NOT NULL; ALTER TABLE product_view ADD CONSTRAINT valid_payload_state CHECK ( (deleted AND payload IS NULL) OR (NOT deleted AND payload IS NOT NULL) ); Represent deletion as a versioned write carrying deleted = TRUE and a null payload. Use the same version predicate for active records and tombstones, updating both payload and deleted from the incoming row. A legitimate newer active revision must restore deleted = FALSE. Tombstone retention must cover retries, delayed delivery, backfills, and supported replay windows. Removing the tombstone removes the information needed to reject older revisions. Identifier reuse adds another complication. If revisions restart, compare an authoritative generation and revision together so generation 7, revision 1 can supersede generation 6, revision 982. Make Rejected Writes Operationally Useful A stale delivery should normally finish as a terminal no-op. Record the rejection and acknowledge the message. Retrying version 108 cannot make it newer than 109. Track applied updates, stale rejections, identical replays, and conflicting revisions separately. Include entity identifiers, incoming revisions, event identifiers, and delivery paths in diagnostic records. A sudden increase in stale rejections can expose a slow dependency, retry backlog, or unexpected replay. The fence protects correctness while those signals help explain the disruption. This approach fits snapshot projections with a meaningful authoritative order. Concurrent independent updates may instead require merge rules or field-level versions. The essential boundary is the write: once a newer revision is accepted, every later mutation must prove that it is allowed to advance that state.
We spend most of our time building mobile apps for businesses, and offline support comes up in almost every project. Users open apps in warehouses, basements, parking garages, and on trains, and they expect their work to be saved anyway. Most React Native applications handle offline mode the same way at first. Wrap fetch in a try/catch, show a toast that says "No connection," and hope the user tries again. That works until your users are field staff, delivery drivers, or anyone who spends half their day without a stable signal. Then "try again" turns into lost orders, duplicate records, and support tickets nobody can reproduce. The pattern our team reaches for is an outbox: every write goes into a persistent local queue first, and a background process drains that queue to the server when it can. It sounds simple. The details are where it gets interesting. The Naive Version and Why It Breaks The first version usually looks something like this: TypeScript async function saveOrder(order: Order) { try { await api.post('/orders', order); } catch { pendingOrders.push(order); // retry later } } There are at least three problems here. First, pendingOrders lives in memory. If the OS kills the app, which both iOS and Android do aggressively in the background, the pending writes are gone. Second, a failed request is not the same as a request that never reached the server. If the connection drops after the server commits the order but before the response arrives, the retry creates a duplicate. Third, nothing decides when to retry. Either you retry in a tight loop and drain the battery, or you wait for the user to do something. A real outbox has to solve all three: persistence, idempotency, and scheduling. The Data Model Each queued write is a small, serializable record: TypeScript type Mutation = { id: string; // also used as the idempotency key endpoint: string; method: 'POST' | 'PUT' | 'PATCH' | 'DELETE'; body?: unknown; attempts: number; nextAttemptAt: number; // epoch ms createdAt: number; }; The id is generated on the device when the user takes the action, not when the request is sent. That's the key decision. The same logical action keeps the same ID no matter how many times it's retried. On React Native, you'll need a polyfill for crypto.getRandomValues before using uuid: TypeScript import 'react-native-get-random-values'; import { v4 as uuid } from 'uuid'; Persisting the Queue Safely We're using AsyncStorage here to keep the example short. For high write volumes, SQLite or MMKV is a better fit, but the structure stays the same. The trap with AsyncStorage is concurrent read-modify-write. If the user saves something while the sync loop is halfway through draining the queue, one of the writes silently overwrites the other. So every queue change goes through a single serialized chain: TypeScript import AsyncStorage from '@react-native-async-storage/async-storage'; const QUEUE_KEY = 'outbox:v1'; let lock: Promise<unknown> = Promise.resolve(); function withQueue<T>( fn: (queue: Mutation[]) => [Mutation[], T] ): Promise<T> { const run = lock.then(async () => { const raw = await AsyncStorage.getItem(QUEUE_KEY); const queue: Mutation[] = raw ? JSON.parse(raw) : []; const [next, result] = fn(queue); await AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(next)); return result; }); lock = run.catch(() => undefined); return run; } export function enqueue( m: Omit<Mutation, 'id' | 'attempts' | 'nextAttemptAt' | 'createdAt'> ) { const item: Mutation = { ...m, id: uuid(), attempts: 0, nextAttemptAt: Date.now(), createdAt: Date.now(), }; return withQueue(q => [[...q, item], item.id]).then(id => { flush(); return id; }); } The outbox:v1 key is versioned on purpose. When the Mutation shape changes in a future release, you'll want to migrate old queues instead of crashing on them. Sending a Mutation Each send returns one of three outcomes. Treating every failure the same is one of the most common mistakes we see in retry logic. TypeScript type SendResult = 'done' | 'retry' | 'drop'; async function send(m: Mutation): Promise<SendResult> { let res: Response; try { res = await fetch(`${API_URL}${m.endpoint}`, { method: m.method, headers: { 'Content-Type': 'application/json', 'Idempotency-Key': m.id, }, body: m.body === undefined ? undefined : JSON.stringify(m.body), }); } catch { return 'retry'; // network error, the server may or may not have it } if (res.ok) return 'done'; if (res.status === 408 || res.status === 429 || res.status >= 500) { return 'retry'; } return 'drop'; // 4xx: retrying the same payload won't help } A 400 or 422 means the payload itself is wrong. Retrying it forever just blocks everything behind it. Those mutations should leave the queue and be shown to the user, or logged, so someone can fix the data. Draining the Queue The sync loop processes the queue in order, one item at a time: TypeScript const MAX_ATTEMPTS = 10; let flushing = false;const MAX_ATTEMPTS = 10; let flushing = false; export async function flush(): Promise<void> { if (flushing) return; flushing = true; try { while (true) { const head = await withQueue(q => [q, q[0]]); if (!head || head.nextAttemptAt > Date.now()) break; const result = await send(head); if (result === 'retry' && head.attempts + 1 < MAX_ATTEMPTS) { await withQueue(q => [ q.map(x => x.id === head.id ? { ...x, attempts: x.attempts + 1, nextAttemptAt: Date.now() + backoff(x.attempts + 1), } : x ), null, ]); break; } if (result !== 'done') reportFailed(head, result); await withQueue(q => [q.filter(x => x.id !== head.id), null]); } } finally { flushing = false; } } Notice that items are removed by id, not by position. New writes can land at the end of the queue while a request is in flight, and this keeps them intact. Backoff uses full jitter. Without it, every device that lost connection at the same moment retries at the same moment too, and your API gets a thundering herd the second a cell tower comes back: function backoff(attempt: number): number { const base = 1_000; const cap = 5 * 60 * 1_000; return Math.random() * Math.min(cap, base * 2 ** attempt); } When to Flush The queue should drain without the user doing anything. Three triggers cover most cases: import NetInfo from '@react-native-community/netinfo'; import { AppState } from 'react-native'; NetInfo.addEventListener(state => { if (state.isConnected && state.isInternetReachable !== false) flush(); }); AppState.addEventListener('change', s => { if (s === 'active') flush(); }); The third trigger is a timer set for the head item's nextAttemptAt, so a retry fires even if the network state never changes. We've left it out here for brevity. Don't trust isConnected alone. A phone on hotel Wi-Fi behind a captive portal reports as connected. That's why the check also looks at isInternetReachable, and why send still has to handle network errors gracefully. The Server Half: Idempotency Keys None of this prevents duplicates unless the server cooperates. The API must remember which keys it has already processed: SQL CREATE TABLE idempotency_keys ( key TEXT PRIMARY KEY, status_code INT NOT NULL, response_body JSONB, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); When a request arrives, the server checks the key inside the same transaction as the business write. If the key already exists, it returns the stored response instead of running the operation again. Old keys can be cleaned up after a day or two, as long as that window is longer than your client's maximum retry period. Trade-Offs Worth Knowing Strict ordering causes head-of-line blocking. One slow mutation delays everything behind it. We accept that because ordering matters for most business data: you can't update an order that hasn't been created yet. If your writes are truly independent, you can process them in parallel per entity instead. Optimistic UI needs a rollback path. If you show the change immediately, a dropped mutation has to reverse it on screen. Otherwise the user sees data that never reached the server. Conflicts are a separate problem. An outbox guarantees delivery, not correctness. If two devices edit the same record offline, you still need a version field and a policy for 409 Conflict, whether that's last-write-wins, a merge, or asking the user. Wrapping Up An outbox turns flaky connectivity from a user-facing error into a background detail. The core ideas are small: persist every write before sending it, give each action a stable ID, classify failures instead of retrying blindly, and make the server idempotent. This is the baseline we start from whenever a mobile app has to work offline. Start with the simplest storage that works, measure how big your queues get in the real world, and only then reach for something heavier.
Almost every distributed system ends up with an asynchronous messaging layer. One service publishes an event, several others consume it at their own pace, and the publisher doesn't wait for them. On Google Cloud, that layer is Pub/Sub. On AWS, it's usually two services wired together: SNS for fan-out and SQS for durable queues. The building blocks are cut differently, and it shows in your code: how you publish, acknowledge, retry, and order messages. This article walks through Pub/Sub in Java, maps it onto SNS and SQS, and shows how MultiCloudJ, an open-source Java SDK from Salesforce, puts both behind one portable API. The Google Cloud Pub/Sub Model Pub/Sub has two core resources: Topic. A named channel that publishers send messages to. Topics are global resources: a publisher in us-east1 and a subscriber in europe-west1 use the same topic without any cross-region plumbing.Subscription. A named, durable stream of messages from one topic. Each subscription gets its own copy of every message published after it was created. Several subscribers on the same subscription share the work, and each message goes to one of them. So fan-out means many subscriptions, and load-balancing means many subscribers on one subscription, with no extra wiring for either. One topic, three subscriptions: two billing workers share a pull subscription, analytics exports to BigQuery, and email is pushed to Cloud Run. Delivery: Pull, Push, or Export Pull. The subscriber asks for messages. The Java client library uses StreamingPull, a long-lived bidirectional gRPC stream, so messages flow as soon as they arrive.Push. Pub/Sub sends each message as an HTTPS POST to an endpoint you own, such as a Cloud Run service. It can attach a Google-signed OIDC token so the endpoint can verify the caller. A success status (102, 200, 201, 202, or 204) is an ack.Export. BigQuery and Cloud Storage subscriptions write messages straight into a table or bucket, with no consumer code at all. Acknowledgment and the Ack Deadline Delivery is at-least-once. A received message must be acked within the subscription's ack deadline (10 seconds by default, up to 600), or Pub/Sub redelivers it. ModifyAckDeadline extends the deadline, and setting it to 0 is a nack: the message becomes available for redelivery right away. The Java client extends leases in the background while your callback runs, for up to an hour by default. A subscription retains unacked messages for 7 days by default, configurable from 10 minutes to 31 days. Topics can also retain messages for up to 31 days, so a new or rewound subscription can replay history with Seek. Publishing and Consuming in Java The native publisher batches messages and returns a future per message. build() throws IOException: Java import com.google.api.core.ApiFuture; import com.google.cloud.pubsub.v1.Publisher; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; Publisher publisher = Publisher.newBuilder(TopicName.of("my-project", "orders")) .setEnableMessageOrdering(true) // required if you set ordering keys .build(); PubsubMessage message = PubsubMessage.newBuilder() .setData(ByteString.copyFromUtf8("{\"orderId\":\"o-123\",\"total\":42.50}")) .putAttributes("type", "order.created") // attributes are string key/value pairs .setOrderingKey("customer-42") // ordered per key, not per topic .build(); ApiFuture<String> messageId = publisher.publish(message); The subscriber registers a callback that acks or nacks each message: Java import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.cloud.pubsub.v1.Subscriber; import com.google.pubsub.v1.ProjectSubscriptionName; MessageReceiver receiver = (msg, consumer) -> { try { process(msg.getData().toStringUtf8(), msg.getAttributesMap()); consumer.ack(); } catch (Exception e) { consumer.nack(); // redeliver now } }; Subscriber subscriber = Subscriber.newBuilder( ProjectSubscriptionName.of("my-project", "orders-billing"), receiver) .build(); subscriber.startAsync().awaitRunning(); Both use Application Default Credentials, so on GKE, Cloud Run, or GCE, no keys appear in code. The Features That Matter in Production Ordering keys. Messages that share an ordering key are delivered in publish order, as long as the subscription has message ordering enabled, and the messages are published in the same region. Messages with different keys can still be processed in parallel.Dead-letter topics. After a configurable number of delivery attempts (5 to 100), Pub/Sub forwards the message to a dead-letter topic instead of retrying forever.Filtering. A subscription can carry a filter on message attributes, such as attributes.type = "order.created", so consumers only get what they care about.Exactly-once delivery. Pull subscriptions can turn on exactly-once delivery. Pub/Sub then won't redeliver a message once its ack has succeeded, and the Java client's AckReplyConsumerWithResponse tells you whether the ack went through. The guarantee holds when subscribers connect in the same region. AWS for Comparison: SNS Plus SQS SNS is the topic: it pushes each message to its subscribers immediately, and consumers can't poll it. SQS is the durable queue: consumers poll it, and a message stays until someone deletes it. For Pub/Sub-style fan-out, you subscribe one SQS queue per consumer group to an SNS topic. The same topology on AWS: an SNS topic fans out to one SQS queue per consumer group. The concepts map closely; the table below lines them up. A few AWS details have no Pub/Sub equivalent: Each queue needs an access policy that lets the topic send to it.SQS has no ack call. You DeleteMessage with the receipt handle from ReceiveMessage.There is no streaming pull. ReceiveMessage long-polls for up to 20 seconds.FIFO adds a 5-minute deduplication window keyed by MessageDeduplicationId.Unless raw message delivery is on, each SQS body is an SNS JSON envelope with your payload in its Message field. Side by Side ConceptGoogle Cloud Pub/SubAWS SNS + SQSServices involvedOneTwo, wired togetherFan-outMultiple subscriptions on a topicSNS topic subscribed by multiple SQS queuesDurable consumer streamSubscriptionSQS queueConsumeStreamingPull, push, or export to BigQuery/GCSSQS polling (max 10 per call), or SNS push to Lambda/HTTPSAckAcknowledgeDeleteMessageAck windowAck deadline: 10s default, 600s maxVisibility timeout: 30s default, 12h maxNackModifyAckDeadline to 0ChangeMessageVisibility to 0OrderingOrdering keys on any topicFIFO topics and queues with MessageGroupIdDead lettersDead-letter topic, 5–100 attemptsRedrive policy, maxReceiveCountMax message size10 MB1 MiB (SQS), 256 KiB by default on SNS, configurable to 1 MiBRetentionSubscription: 7 days by default, up to 31. Topic: up to 31 daysSQS: 4 days by default, up to 14. SNS FIFO archive: up to 365 daysReplaySeek to a timestamp or snapshot, on any topicSNS FIFO archive and replay only. Standard topics and SQS can't replay Pub/Sub has fewer moving parts. A new consumer group is one subscription. On AWS it's a queue, a subscription, and a queue policy.Ordering is cheaper to adopt on Pub/Sub. You add a key to a topic you already have. On AWS, you need FIFO resources from the start, because you can't convert a standard queue to FIFO.SQS gives you a longer ack window. Long-running jobs fit the 12-hour visibility timeout. On Pub/Sub, you rely on the client extending the lease.Replay is broader on Pub/Sub. Seek works on any subscription, which makes reprocessing after a bad deploy a routine operation. On AWS, only FIFO topics with archiving enabled can replay. One Interface for Both: MultiCloudJ If your service runs on both clouds, these differences become if (cloud == GCP) branches through your messaging code. MultiCloudJ removes them. Its pubsub module has two portable clients, TopicClient and SubscriptionClient. They delegate to an abstract driver that owns batching, prefetching, ack batching, and error mapping, and a provider module per cloud makes the API calls. Providers are discovered with Java's ServiceLoader and selected by an ID string, so switching clouds is a configuration change. MultiCloudJ's layers: one portable API, provider drivers underneath. Add the Dependencies Add the client plus a provider module for each cloud. Your code never imports the provider modules: XML <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-client</artifactId> <version>0.4.11</version> </dependency> <!-- Google Cloud Pub/Sub --> <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-gcp</artifactId> <version>0.4.11</version> </dependency> <!-- AWS SNS and SQS --> <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-aws</artifactId> <version>0.4.11</version> </dependency> Only the provider ID and resource name change between clouds: CloudTopic provider IDTopic nameSubscription provider IDSubscription nameGoogle Cloudgcpprojects/my-project/topics/ordersgcpprojects/my-project/subscriptions/orders-billingAWS (SNS)awssnsarn:aws:sns:us-east-1:123456789012:ordersawsSQS queue name, e.g. orders-billingAWS (SQS)awssqsSQS queue name or queue URLawsSQS queue name, e.g. orders-billing On AWS, a subscription is always an SQS queue, whether you publish to SNS or straight to SQS. Send a Message With MultiCloudJ Java import com.salesforce.multicloudj.pubsub.client.TopicClient; import com.salesforce.multicloudj.pubsub.driver.Message; public class PublishOrder { public static void main(String[] args) throws Exception { String provider = System.getenv("PUBSUB_TOPIC_PROVIDER"); // gcp, awssns, or awssqs String topicName = System.getenv("PUBSUB_TOPIC"); TopicClient.TopicClientBuilder builder = TopicClient.builder(provider) .withTopicName(topicName); String region = System.getenv("REGION"); // e.g. us-east-1 on AWS if (region != null) { builder.withRegion(region); } try (TopicClient topic = builder.build()) { Message message = Message.builder() .withBody("{\"orderId\":\"o-123\",\"total\":42.50}") .withMetadata("type", "order.created") .build(); topic.send(message); // blocks until accepted } // close() flushes pending batches } } The driver batches concurrent sends: up to 1,000 per Publish on GCP, and 10 per PublishBatch or SendMessageBatch on AWS. Metadata becomes Pub/Sub attributes or SNS/SQS message attributes. Receive Messages With MultiCloudJ Java import com.salesforce.multicloudj.pubsub.client.SubscriptionClient; import com.salesforce.multicloudj.pubsub.driver.Message; import java.nio.charset.StandardCharsets; import java.time.Duration; public class ConsumeOrders { public static void main(String[] args) throws Exception { String provider = System.getenv("PUBSUB_SUBSCRIPTION_PROVIDER"); // gcp or aws String subscriptionName = System.getenv("PUBSUB_SUBSCRIPTION"); SubscriptionClient.SubscriptionClientBuilder builder = SubscriptionClient.builder(provider) .withSubscriptionName(subscriptionName) .withNackVisibilityTimeout(Duration.ofSeconds(30)); // nack delay, default 0 String region = System.getenv("REGION"); if (region != null) { builder.withRegion(region); } try (SubscriptionClient subscription = builder.build()) { while (!Thread.currentThread().isInterrupted()) { Message msg = subscription.receive(); // blocks; the driver prefetches try { String body = new String(msg.getBody(), StandardCharsets.UTF_8); process(body, msg.getMetadata()); subscription.sendAck(msg.getAckID()); // batched in the background } catch (Exception e) { subscription.sendNack(msg.getAckID()); // redelivered after 30s } } } } private static void process(String body, java.util.Map<String, String> metadata) { // your business logic } } This loop runs unchanged on both clouds. The driver translates each call: Portable callGCP driverAWS driverreceive()Pull, up to 1,000 per callReceiveMessage, up to 10 per callsendAck(id)AcknowledgeDeleteMessageBatchsendNack(id)ModifyAckDeadline, capped at 600sChangeMessageVisibilityBatch, capped at 12hgetMetadata()Message attributesSQS attributes, merged with SNS attributesgetAttributes()GetSubscription (name, topic)GetQueueAttributes (queue ARN) The driver also absorbs differences you'd otherwise handle yourself: Adaptive prefetching. receive() reads from a buffer the driver keeps about 2 seconds deep, based on your processing rate, so messages don't sit past their ack deadline.Ack batching. sendAck returns immediately; acks flush in batches of up to 1,000 on GCP and 10 on AWS. sendAcks returns a CompletableFuture if you need confirmation.Nack backoff. sendNack(id, Duration) overrides the subscription default per message. The GCP driver groups nacks by deadline, since ModifyAckDeadline takes one deadline per request.SNS envelope unwrapping. Without raw delivery, the AWS driver unwraps the SNS envelope, so you see the original body and metadata, as on GCP.FIFO through metadata. On AWS, the MessageGroupId and DeduplicationId metadata keys become the native FIFO fields.Portable errors. Provider exceptions map to one SubstrateSdkException hierarchy. What the Abstraction Doesn't Hide Resources are provisioned elsewhere. Topics, subscriptions, queues, SNS-to-SQS wiring, and dead-letter policies still come from Terraform or your platform tooling.Pub/Sub-only features stay native. Filters, exactly-once delivery, push and export subscriptions, and Seek are configured on the resources or used through the native client. The GCP driver also doesn't set ordering keys.The GCP driver uses unary Pull, not StreamingPull. That keeps one batching model across clouds, but the native Subscriber will deliver lower latency for very high-throughput subscriptions.Ack windows still differ. The same nack timeout is capped at 10 minutes on GCP and 12 hours on AWS. Size your processing time to the smaller window. Conclusion Google Cloud Pub/Sub folds fan-out, durable queuing, and replay into one service. AWS gets there by combining SNS and SQS, with more resources to wire and different API verbs. On Google Cloud, subscriptions, ordering keys, and Seek give you more with less configuration. If you run on both, keep the differences out of your business logic: put MultiCloudJ's TopicClient and SubscriptionClient at the boundary, pick the provider in configuration, and use the native client for the few features only one cloud offers.