The final step in the SDLC, and arguably the most crucial, is the testing, deployment, and maintenance of development environments and applications. DZone's category for these SDLC stages serves as the pinnacle of application planning, design, and coding. The Zones in this category offer invaluable insights to help developers test, observe, deliver, deploy, and maintain their development and production environments.
In the SDLC, deployment is the final lever that must be pulled to make an application or system ready for use. Whether it's a bug fix or new release, the deployment phase is the culminating event to see how something works in production. This Zone covers resources on all developers’ deployment necessities, including configuration management, pull requests, version control, package managers, and more.
The cultural movement that is DevOps — which, in short, encourages close collaboration among developers, IT operations, and system admins — also encompasses a set of tools, techniques, and practices. As part of DevOps, the CI/CD process incorporates automation into the SDLC, allowing teams to integrate and deliver incremental changes iteratively and at a quicker pace. Together, these human- and technology-oriented elements enable smooth, fast, and quality software releases. This Zone is your go-to source on all things DevOps and CI/CD (end to end!).
A developer's work is never truly finished once a feature or change is deployed. There is always a need for constant maintenance to ensure that a product or application continues to run as it should and is configured to scale. This Zone focuses on all your maintenance must-haves — from ensuring that your infrastructure is set up to manage various loads and improving software and data quality to tackling incident management, quality assurance, and more.
Modern systems span numerous architectures and technologies and are becoming exponentially more modular, dynamic, and distributed in nature. These complexities also pose new challenges for developers and SRE teams that are charged with ensuring the availability, reliability, and successful performance of their systems and infrastructure. Here, you will find resources about the tools, skills, and practices to implement for a strategic, holistic approach to system-wide observability and application monitoring.
The Testing, Tools, and Frameworks Zone encapsulates one of the final stages of the SDLC as it ensures that your application and/or environment is ready for deployment. From walking you through the tools and frameworks tailored to your specific development needs to leveraging testing practices to evaluate and verify that your product or application does what it is required to do, this Zone covers everything you need to set yourself up for success.
Terry: A Live File Tree and Review Gate for Claude Code
Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist
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.
Having mapped the system and classified its asynchrony, it's time to move on to the failures that we can expect, their detection, and mitigation. This is the technical core of the article. Ideally, a comprehensive test suite walks every cell of the taxonomy below for every component and network pair in the system map, rather than enumerating failures ad hoc. Safety and Liveness: The Two Properties Behind Everything That Follows The notion of the correct software is notoriously fuzzy: obviously, a system is correct if it does what it is supposed to do. However, this gives no objective criteria for determining whether a system is correct. We need to be able to think rigorously about the system’s guarantees, capabilities, and limitations. We will focus on liveness and safety as described by Leslie Lamport. Every failure in this part matters for one of two reasons: it can make the system do something it must never do, or it can stop the system from doing something it must eventually do. Distributed systems theory gives these two ideas names, and the rest of this part leans on them. It is worth fixing them with simple examples before the taxonomy begins. A safety property says that something bad never happens. A liveness property says that something good eventually happens. The two are independent: a system can satisfy one and violate the other. examplesafety: Something bad never happensLiveness: something good eventually happens Traffic light at a crossing The lights never show green in both directions at once. Every direction eventually gets a green. Elevator The doors never open while the cabin is between floors. Every pressed call button is eventually answered. Order pipeline A customer's card is never charged twice for one order, and never charged without the stock being reserved. Every order eventually ends up confirmed or cancelled. You need both, because each is trivially satisfied by giving up the other. A traffic light stuck on red in every direction is perfectly safe, and useless. An elevator that moves the moment any button is pressed, doors or no doors, is as responsive as it gets, and dangerous. A pipeline that rejects every order never double-charges anyone; a pipeline that retries blindly until something succeeds makes progress and sometimes charges a card twice. Ideally, we want to build systems where every possible system behavior satisfies both properties. Why the Distinction Matters for Testing The two properties are tested in different ways, and confusing them is a common problem. A safety violation can be caught in a finite observation: at some specific moment, two charges exist for one order, and an assertion or invariant check can point at it. Safety tests therefore tend to be exact, and they can run continuously alongside any other test as an invariant. A liveness violation cannot be caught that way. "Eventually" has no deadline, so no finite observation can prove that the good thing will never happen; the system may simply be slow. In practice, a liveness test is always a bounded approximation, such as "the order is confirmed within 30 seconds." The three regimes from Part 1 show how this plays out. In the partially synchronous core, a calibrated bound is meaningful. With a weak notion of time, it is only a suspicion. With no notion of time, it is a business policy about when to escalate to a human, which is why that regime relies on reconciliation rather than on waiting. How Failure Forces a Choice When a failure hits, a system often cannot keep both properties. It can keep safety and give up liveness by stopping rather than risk a mistake. It can keep liveness and give up safety by carrying on and accepting that it may misbehave for a while. Or, at the best and most expensive end, it can hide the failure entirely and keep both. Section 2.3 names these three outcomes (fail-safe, nonmasking, and masking) and explains how to write assertions that match the contract a component actually provides. Section 2 also uses the two properties as its organizing lens: failure detection is what protects safety, because a system that notices trouble can stop doing dangerous things. Failure mitigation is what restores liveness, because it lets the system resume making progress. Failure Modes 1. Component Failure Modes Crash stop, omission, and crash recovery will be covered here. Byzantine failures are not covered but are only mentioned in the table below for completeness. failure typedescriptiontest implication Crash-Stop The component halts permanently and performs no further steps. The simplest to test: kill the process and verify that the rest of the system degrades or routes around it correctly. Omission The component pauses for an arbitrary duration, then resumes exactly where it left off with no state lost. Test with process suspension (SIGSTOP and SIGCONT, or docker pause), not process kill. It is a meaningfully different failure and is often untested. Crash-Recovery The component pauses, resumes, and may have lost some volatile state while keeping durable state. Kill and restart with a controlled subset of state wiped, for example an in-memory cache cleared while the disk volume is intact. This is where "did we persist what we thought we persisted" bugs live. Byzantine The component behaves arbitrarily, including sending contradictory or deceptive messages to different peers. Relevant only where not every participant is trusted (e.g., cryptocurrency). To test for component failures, we could use, for example, fault injection. Stopping, suspending, and restarting components, or exhausting their resources, shows how the rest of the system reacts. Component tests against real dependencies show whether durable state really survives a restart. Transactional-integrity tests check that a write and the message announcing it cannot be separated by a crash. State-transition tests check that a recovering component does not accept events its state machine should refuse. Recovery and failover testing measures how long recovery takes and what, if anything, is lost. Part 4 maps each of these to the level where it is cheapest. 2. Network Failure Modes Message loss: the network does not deliver.Message duplication: the network delivers more than once.Message reordering: the network delivers out of order. A network that exhibits any of these is an unreliable network. An unreliable network is the default assumption for everything except same-process function calls. The model assumes the network does not lie: if it delivers a message, some component in the system really sent it. The three network failures map naturally to families of tests. Duplication is addressed by idempotence and duplicate-delivery tests, which feed the same message to a handler several times. Reordering is addressed by permutation tests, which feed a short event sequence in every order, and by property-based tests, which generate far more orderings than anyone would write by hand. Loss is addressed by reconciliation checks, which compare what was sent with what was acknowledged, and by tests of the retry behavior around it. Network-level fault injection, which adds latency, drops, duplicates, and reorders traffic between components, then confirms in a running system that these defenses hold. Contract tests complement all of this by checking that both sides agree on what a message means in the first place. For more details, the section on examples for message handlers (Part 3, section 1.6) could be useful. 3. Spatial and Temporal Classification Spatial: application-level versus platform-level. A failure is application-level if the application layer is the lowest layer that can meaningfully interpret and resolve it (for example, InsufficientFunds). It is platform-level if a lower layer can and should resolve it (for example, CouldNotConnect, resolved by reconnecting). This is the end-to-end argument: handle a failure at the lowest layer that can handle it correctly and completely. It also tells you where the corresponding test belongs: Application-level failures are tested with business-logic-level cases: does the checkout flow correctly reject and compensate on InsufficientFunds?Platform-level failures are tested with infrastructure-level fault injection: does the HTTP client retry correctly on connection failure, with correct backoff? This usually uses the network tooling above rather than application fixtures. Temporal: transient, intermittent, permanent. These differ by whether a first failure makes a second one more likely, and by how they are repaired. Transient: no elevated recurrence probability, self-repairing quickly (a single dropped packet). Test with single-shot fault injection: fail once, verify that an immediate retry succeeds.Intermittent: elevated recurrence probability, self-repairing but after some delay (a flapping link, a stale routing table). Test with repeated, clustered fault injection over a sustained window. A single-shot test will never surface an intermittent failure mode, which is why soak testing and scheduled chaos matter.Permanent: certain recurrence, requires manual repair (an expired certificate). This is effectively an integration test with the dependency held down for the whole test: verify that the system escalates to fail-safe behavior and alerting rather than retrying forever. Pairing with load. Recurring fault injection ("cut connectivity for 10 seconds every 2 minutes for an hour") is what intermittent failure simulation needs. It should be combined with concurrent load, because intermittent failures may only manifest under load (connection pool starvation, resource exhaustion). So the combination is usually necessary rather than optional. 4. Which Failures Dominate in Which Scenario The taxonomy applies everywhere, but its cells are not equally important in every regime. Use this table to prioritize the first pass of a test plan. failureScenario 1: partially synchronousScenario 2: async, weak timeScenario 3: async, no time Crash-Stop, Crash-Recovery High: autoscaling and rolling deploys are constant Medium: mostly device app kills and region outages Medium: the partner's batch job can crash silently Omission (pauses) High: GC and scheduler pauses are the main source of false failure detection Medium Low: pauses are lost in the noise of arbitrary delay Message loss Low to medium: broker-level durability usually covers it High: sync-on-reconnect and flaky links High: files never picked up or never returned Message duplication Medium: at-least-once consumers and retries Very high: resend-on-reconnect is by design High: repeated file drops and re-sent batches Message reordering Low within a partition; higher across partitions Very high: offline queues and multi-region replication Medium: response files can arrive out of order Clock skew and drift Medium: small but relevant under contention Very high: device clocks are untrusted Not applicable: no shared clock is assumed at all Transient versus permanent Mostly transient and intermittent All three, with long intermittent partitions Mostly permanent or human-repaired Detection and Mitigation as Testable Properties Failure handling splits cleanly into two mechanisms that should be tested separately: detection (recognizing that a failure occurred) and mitigation (recovering from it). Detection is fundamentally about preserving safety: once you suspect trouble, stop doing anything dangerous. Mitigation is about restoring liveness: resume making progress once the trouble is over or has been worked around. 1. Testing Detection Detection mechanisms follow two patterns. In a pull design, the observer polls the observed component and expects a timely answer. In a push design, the observed component emits heartbeats at a set frequency. In both, the failure witness is a timeout. A point worth internalizing, and worth communicating to stakeholders who file bugs against "flaky" tests: in a partially synchronous or asynchronous system over an unreliable network, no failure detector can be both complete (catches every real failure) and accurate (never flags a non-failure). The obstacle is structural, not an engineering gap. The detector simply cannot tell "delayed" from "lost." Practically, that means: Detection tests should verify tuned behavior (does the timeout or heartbeat interval match your actual SLA and network characteristics?), not perfect behavior.Some of the flakiness in async test suites accurately reflects this impossibility and is not evidence that the tests or the system are broken. The fix is often to make the detector's trade-off intentional and documented, not to try to eliminate all false positives.Ask who supervises the supervisor. Every detector is itself a component that can fail. Somewhere the chain ends in human intervention, and that hand-off should be tested too (does the alert actually fire, does the on-call runbook work?). The thresholds of a circuit breaker or health check are testable units. Boundary-value tests with controlled time assert that the circuit opens and closes exactly at the configured thresholds. They are also kept separate from integration tests that verify end-to-end behavior once it does. Mutation testing, which deliberately breaks the comparison operators and counters in that logic, shows whether those tests would notice a regression. Alerting rules are testable too, against synthetic data, so that the hand-off to a human is checked as well. 2. Testing Mitigation Mitigation is either backward recovery (return to a state equivalent to the initial one, via compensation) or forward recovery (push through to a state equivalent to completion, via retries). Test each explicitly: Backward recovery and compensation tests. Inject a failure partway through a multi-step process and assert that compensating actions (refund, release reservation) run correctly. Compensations can fail too, so they must themselves be idempotent and retriable. There must be an escalation path to a human when they cannot complete (the refund that fails is the classic example).Forward recovery and retry tests. Verify retry count and backoff strategy: immediate retry for an assumed transient failure, backoff and retry for an assumed intermittent one, suspend and alert for an assumed permanent one. Critically, verify that a retry does not cause duplicate side effects when the first attempt actually succeeded, but its response was lost. Service virtualization, in which a dependency is scripted to fail N times and then succeed, is the cleanest way to test retry and backoff logic deterministically without depending on real network chaos. Component tests against real dependencies (a real broker, a real database) then close the gap between "my retry logic is unit tested" and "my retry logic works against the real client library's real failure modes." 3. Masking, Nonmasking, and Fail-Safe as a Test-Design Lens Before writing a test against a component under fault injection, decide which of the three failure-tolerance types the component is designed to provide, and write assertions that match that contract. safety heldsafety not held Liveness held Masking: the failure is fully hidden. Assert normal behavior even during fault injection. Nonmasking: progress continues but may misbehave. Assert eventual correctness, not correctness during the fault window. Liveness not held Fail-safe: assert that the system halts or rejects rather than risking a bad state. Not failure tolerant. Generally unacceptable. The classic example is a FIFO queue. A masking queue keeps delivering in order despite the fault. A nonmasking queue keeps delivering but may reorder during the fault. A fail-safe queue stops delivering rather than risk reordering. Asserting "no errors, ever" is an unstated masking assumption that most real components do not provide, and it can keep your suite perpetually and legitimately red. Wrapping Up This part explained liveness and safety in software. It enumerated what can fail, at the component level and the network level. It showed how to test detection and mitigation as separate, independently verifiable properties. Part 3 turns to the messages themselves: what delivery and processing guarantees are actually achievable, how to test idempotence as its own contract, and how to turn all three parts of this series into an observability setup and a checklist you can use directly in a test plan.
The Number That Didn't Make Sense A few months ago, I was looking at our delivery numbers, and something felt off. Pull requests merged were up. Commits were up. By every activity metric we tracked, the team was producing more than it had before we rolled out AI coding tools in earnest. And yet features were not landing faster. If anything, the time from "code complete" to "in production" had gotten worse. I sat in on a few review queues to understand why. What I found was not lazy reviewers or careless authors. It was six senior engineers staring at pull requests that were three, four, five times the size they used to be — trying to hold an entire AI-generated change in their heads and decide whether they trusted it. We had automated writing code. We had not changed anything about how we verified it. So the bottleneck didn't disappear. It moved. This Is Not Just My Team The data coming out this fall says the same thing at scale. Qodo's 2026 State of AI Code Quality Report, published in September, found that developers and engineering leaders independently ranked the same problem first: reviewing and validating AI-generated code is now the top bottleneck preventing AI from actually accelerating delivery. It was also the most-cited quality and governance gap among leaders, at 48%. Other analyses put numbers on the queue itself. AI-generated pull requests wait far longer for review than human-written ones. Review time has climbed sharply even as merge counts climb. One widely cited analysis of millions of pull requests described the gap plainly: developers feel about 20% faster with AI, and measure about 19% slower. That gap — feels faster, ships slower — is the tell. If your team feels busy and productive and your releases are still slipping, look at the review queue before you look anywhere else. There is a debate on Hacker News right now about whether AI is lowering code quality. I think that debate is asking the wrong question. The sharper version I saw in that thread was this: if AI-generated code is lowering your quality, that is a management failure, not a tool failure. I agree with that more than I'm comfortable with. Because it puts the problem on my desk, not the vendor's. Why Review Breaks First Review was designed for a world where writing code was the expensive part. A human author wrote a change slowly, understood most of it, and a reviewer checked the parts the author might have missed. The sizes were manageable because human typing speed was a natural limiter. Nobody opened a 900-line pull request on a Tuesday afternoon by accident. Agents removed that limiter, and nobody redesigned what came next. Now the author often didn't write the code in the traditional sense at all. They prompted it, skimmed the output, and opened the PR. Which means the first person to truly read the code is the reviewer. Review stopped being a check. It became the reading. Add one more thing: reviewers don't trust this code the way they trust a colleague's. Qodo calls the extra effort a "trust tax" — reviewing AI code takes about the same clock time as before for many developers, but with noticeably more cognitive effort. I recognize that tax. You read an AI change differently. You are not just asking, "Is this right?" You are asking, "Does the author actually know why this is here?" Multiply that by twenty or thirty PRs a day across a team and the math stops working, no matter how good your engineers are. What I Changed — and What I Didn't My first instinct was wrong. I considered adding review capacity: rotate more seniors into review, set response-time targets, nag the queue down. That treats review like ticket triage. I have lived that life before in operations, where the answer to a growing queue was always more hands on the queue — right up until we automated the queue itself. Queues that grow because of a system design problem don't get fixed by staffing them harder. So we changed the system instead. We tiered review by risk, not by habit. A config change, a test addition, and a change to a production data path used to get the same review ritual. They don't anymore. Low-risk, reversible changes get a lighter path — automated checks, an agent pre-review, and one human who is accountable for the merge. High-risk changes get the opposite: smaller scope, mandatory second reviewer, and no merge until someone can explain the change without the AI summary open in front of them. We made PR size a team problem again. Agents will happily generate a sweeping change because sweeping changes are easy to generate. We set an expectation that large changes get split before review, by the author, not discovered by the reviewer. If a change is too big to review well, it is too big to merge. That one rule did more for our queue than any tool we bought. We put the agent to work on review — inside an authority boundary. An agent pre-reviews for the mechanical things humans are bad at catching when they're tired: missing tests, inconsistent patterns, risky calls, changes that don't match the description. It posts that as a first pass. It does not approve. It does not merge. Approval is a judgment call, and in my world judgment calls stay with humans. This is the same authority envelope I apply to agents in operations: automate the execution, keep the irreversible decisions with people. We started measuring verification, not just production. For years my dashboards celebrated output: PRs merged, story points, commits. Now I want to see review wait time, PR size distribution, rework after merge, and how often a change that passed review still caused an incident. If AI is going to be judged, judge the whole workflow, not the typing. The Part Leaders Keep Missing Here is the uncomfortable part for people in roles like mine. Ninety percent of engineering leaders in that Qodo study said they were confident reporting AI's impact to executives or the board. Only 45% said they had evidence tracing AI activity to the code changes it produced. Read that again. Most of us are reporting confidence we cannot actually trace. I don't think that's dishonesty. I think it's that our metrics were built for the old workflow, where output was a decent proxy for progress. It isn't anymore. When an agent can produce output on demand, output stops meaning anything. Verification is where the value — and the risk — actually sits now. So if you are a director or a head of engineering being asked "what are we getting for our AI spend?", the honest place to start is not a productivity chart. It's three questions: Can you trace which changes in production were agent-generated? Can you show what your review system caught before merge, and what it missed? And is your time-to-production getting better, or just your time-to-first-draft? If you can't answer those, you don't have an AI strategy yet. You have an AI purchase. Where This Goes Next I don't believe the answer is less AI code. The genie is not going back in the bottle, and honestly, I wouldn't put it back if I could. The agents are good at the execution work. That's the same lesson I learned moving operations from manual runbooks to agentic systems: let the machines do the work that doesn't require judgment, and protect human time for the work that does. Review is judgment work. It just got buried under a pile of execution volume. The teams that win this next phase won't be the ones that generate the most code. They'll be the ones that rebuilt verification — review, testing, evals, observability — to run at the same speed as generation. That's an engineering leadership job. It's not a tooling purchase, and it's not a hiring plan. It's the job. At least, these days, it's mine.
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.
Ask ten QA engineers what it means to "test an async system," and you will get ten different answers. Most answers are incomplete in the same way: mock the queue, add a retry, assert eventual consistency with a sleep-and-poll loop, ship it. This works until it does not, usually in production, usually under load, and usually in a way that is expensive to diagnose. And that's because the failure was never reproduced in a controlled environment. The problem is not a lack of effort. It is a lack of a model. You cannot design a comprehensive test strategy for a distributed, asynchronous system without first answering three questions, in order: What components and networks are actually involved? Not the logical architecture diagram, but the real one, including the queue, the load balancer, the connection pool, the DNS layer, and every hop a message takes.How asynchronous is the system? Is it synchronous with tight SLAs and occasional hiccups, or genuinely asynchronous with no meaningful timing guarantees at all? These need entirely different test strategies.What failure modes are structurally possible at each layer? Not "what has broken in production before" but what can break, given the components and the degree of asynchrony you just established. Most test plans skip the first two questions and jump to failure scenarios taken from incident postmortems. That produces a suite that is reactive and incomplete: you are testing the failures you have already witnessed, not the failures your architecture makes possible. This article builds the framework in that order. Part 1 (this part) maps the system and classifies its asynchrony through three concrete scenarios. Part 2 enumerates the failure space. Part 3 looks at what a message can actually promise and what observability testing needs. A fundamental checklist is provided that you can lift into a test plan. Part 4 wraps up into a technique-by-level test strategy. Mapping the System Under Test A distributed system is a set of concurrent components that communicate by sending and receiving messages over a network. Each component owns its local state exclusively; no component can directly observe another's state. The network has state too: messages in flight, buffers, retries. Components, Network, and Local State This has an important practical consequence: you cannot write a correct test for a distributed interaction by reasoning about one component's code. A unit test that mocks the network as a reliable, instantaneous pipe is not testing the distributed behavior. It is testing the sequential logic that happens to run on top of it. Both kinds of test are necessary; neither is sufficient alone. Before writing a single async test, produce an inventory: Components. Every service, process, thread pool, or actor that independently executes steps. A single service with an internal job queue is itself a distributed system with two components (the request handler and the worker) and a network (the queue).Networks. HTTP calls, gRPC streams, Kafka topics, Redis pub/sub, an in-memory event bus, a database replication stream. Each is a distinct network with different loss, duplication, and reordering characteristics, and each must be modeled separately.Local state ownership. What does each component hold that nothing else can see directly? This tells you where race conditions are even possible and where component-level isolation is needed in tests. Choosing Your Unit of Composition Components are rarely atomic. A "payment service" is usually a composition: an API layer, a queue consumer, a database, maybe a cache. Whether you treat it as one black box or as four interacting parts is a modeling choice, not a fact about the system, and it determines testing boundaries. A practical rule: pick the coarsest grain that still lets you inject the specific failure you are testing for. To test "what happens when the payment service is unreachable", treat it as atomic and inject faults at its network boundary. To test "what happens when the payment service crashes between debiting and confirming", you need the white-box view. The Running Example One scenario recurs throughout the article: an order-processing pipeline. A client places an order through an API gateway, which publishes an OrderPlaced event to Kafka. An inventory service consumes it and reserves stock, publishing StockReserved. A payment service consumes that and charges the customer's card, publishing PaymentCompleted. A notification service consumes that and sends a confirmation email. It is four components, several networks, and a lot of ways to go wrong. The next section shows how this pipeline behaves according to three different system models depending on where you draw its boundary. How Asynchronous Is the System? Three Scenarios Not every part of a distributed system is asynchronous to the same degree. Conflating them is one of the most common mistakes in async test design. The theory offers a useful vocabulary: Synchronous. Components share a clock (or one with a known maximum deviation), and messages arrive within a known bound. A missing message means a failure, with certainty. A timeout is a reliable witness.Asynchronous, no notion of time. No component has any clock, and events take arbitrary time. Timeouts cannot be used at all. This is mostly a theoretical model, but it is a description of interactions with no timing contract whatsoever.Asynchronous, weak notion of time. Components have local clocks that are not synchronized and have unknown deviation. Events take arbitrary time. Timeouts can be set, but a timeout firing means only "nothing arrived in my window", not "something failed".Partially synchronous. Synchronous most of the time and asynchronous some of the time. This is a popular model for production systems. Purely synchronous systems do not exist in practice, so the interesting testing problems live in the other three. The same order pipeline falls into each of them, depending on the deployment and integration context. For each scenario below, we do four things: First, we describe the setup. Second, we classify its timing characteristics precisely. Third, we walk through some basic edge cases that follow from that classification. Finally, we note the testing implications that Part 4 lays out level by level. Each diagram uses a consistent visual language. Teal marks the core region (scenario 1), purple marks the multi-region and mobile edge (scenario 2), coral marks the partner batch integration (scenario 3), gray marks neutral components, and amber marks the timing hazard specific to that scenario. Solid arrows are normal calls or messages; dashed arrows are links with no timing guarantee. Scenario 1: Partially Synchronous, the Pipeline Inside One Cloud Region The whole pipeline runs inside a single AWS region and VPC: an API gateway, a Kafka cluster, and inventory, payment, and notification services, spread across availability zones with autoscaling and NTP-synchronized clocks. The client talks to the gateway synchronously. Everything after that is asynchronous over Kafka: the gateway publishes OrderPlaced; inventory consumes it and publishes StockReserved; payment consumes that and publishes PaymentCompleted; notification consumes that and sends the email. The double-headed arrows in the diagram mark services that both consume and publish. Figure 1. Scenario 1: the full order pipeline inside a single region. Timing is well-behaved almost all the time. Classification Mostly synchronous. The p99 gRPC latency is well bounded (say, under 200 ms). Consumer lag is usually sub-second, and clock skew is in the tens of milliseconds. But it periodically and unpredictably degrades: garbage-collection pauses, autoscaling events, one availability zone having a bad five minutes, a noisy neighbor stealing CPU. It is synchronous almost all the time and asynchronous-like at unpredictable moments. Those unpredictable moments matter disproportionately because happy-path tests never visit them. Edge Cases and Difficulties The timeout-tuning tension. Too tight, and legitimate load spikes are misclassified as failures, triggering retries that add load to an already stressed system. Too loose, and real failures take too long to detect, holding connections and threads open. There is no universally correct value. It must be derived from the actual latency distribution of the dependency, not chosen as a round number.Retry storms. Because the system is usually fast, clients are not designed for widespread simultaneous slowness. When a real degradation hits, many clients cross their timeout at about the same moment and retry at about the same moment, a thundering herd that arrives exactly when the system can least absorb it. This failure mode requires concurrent load and partial degradation together; neither alone produces it.Partial, localized degradation. One AZ slow while the others are fine disappears in an aggregate p99 metric across the fleet. Tests that assert on aggregate SLAs miss it entirely.Momentary asynchrony from pauses. A stop-the-world GC pause turns a normally synchronous call into something that briefly behaves like the weak-time model below: the caller genuinely cannot distinguish "slow" from "dead" during that window, even though this pair of components behaves synchronously 99.9% of the time.Small but nonzero clock skew. It is precisely during the stressful moments above, when skew-sensitive ordering logic is exercised under contention, that a "small" skew stops being negligible. What This Means for Testing Because timeouts are meaningful here, the central testing questions are whether they are calibrated and whether the system stays stable when load and degradation arrive together. Cheap, deterministic tests can check the boundary logic of timeouts and retries. Whether retry storms and cascades appear can be answered at the system level, with realistic load and partial degradation combined. Calibration has to be re-validated in production, because the latency distribution drifts. Scenario 2: Asynchronous With a Weak Notion of Time, Multiple Regions and Offline Mobile Clients The same pipeline now runs in three regions. Each region has its own gateway, Kafka cluster, and core services, and each holds its own replica of order and inventory state. Regions replicate to one another asynchronously. The customer-facing client is a mobile app that lets someone add items and place an order while offline: actions queue on the device and sync whenever connectivity returns, which could be seconds later or, for a traveler in airplane mode, most of a day later. The app connects to the nearest region over a link that can drop at any time. Figure 2. Scenario 2: three regions running the full pipeline, replicating asynchronously, with an offline-capable mobile client. Classification Every component has some local clock (the phone and each region's NTP-synchronized servers). However, nothing is meaningfully synchronized across the boundary between a phone and the backend, or reliably across regions during a partition. Delays are arbitrary. This is the weak-notion-of-time model as defined: a component can still set a local timeout and treat it as "suspiciously long". It has no basis for trusting a timestamp that crossed a component boundary. The difference from scenario 1 is not "slower". It is "no shared basis for time", which changes which techniques are even valid. Edge Cases and Difficulties Client timestamps cannot be trusted for cross-user ordering. A phone with the wrong timezone or auto-time-sync disabled attaches a timestamp that does not reflect true causal order. A naive "last write wins by timestamp" resolution silently picks the wrong winner whenever a device clock is wrong. At mobile scale, wrong device clocks are routine.Sync-on-reconnect manufactures reordering and duplication by design. The client does not reliably know which queued actions synced before the connection dropped, so it must be prepared to resend. The server-side handlers must treat duplicate and out-of-order delivery as the normal case, not an edge case."Failed" and "delayed" are indistinguishable from the client's perspective. When connectivity itself is arbitrary, deciding when to show the user an error is a product decision in technical clothing. If it is not explicitly designed and tested as a UX decision, it defaults to whatever an arbitrary client-side timeout produces.Replication lag is unbounded under partition. This produces the classic "I just placed the order, and it's gone" bug: a read served by a region that has not caught up appears to contradict something the user just did through another region.Correct ordering requires logical, not physical, clocks. Establishing happened-before relationships (with vector clocks, CRDTs, or similar) becomes necessary. Testing "did we establish the correct causal order" is a fundamentally different exercise from testing "did we respond within N milliseconds". What This Means for Testing Here the emphasis shifts. Correctness depends on logical ordering and idempotent replay rather than on clocks. Ordering and merge logic deserve exhaustive exploration instead of hand-picked examples. Clocks need to be deliberately wrong in tests, disconnections need to be long and open-ended, and replication lag and reconciliation conflicts need continuous measurement in production. Scenario 3: Asynchronous With No Notion of Time, Batch Integration With an External Partner Inventory fulfillment is now delegated to an external wholesale distribution partner. Inside your system, the pipeline is unchanged, but an adapter service consumes fulfillment events from Kafka and writes a batch order file to an outbound SFTP folder. The partner's batch job picks the file up whenever it happens to run. This could be minutes or several days later, and eventually may drop a response file in an inbound folder, or may not. There is no heartbeat, no shared clock, and no acknowledgment protocol beyond "a response file shows up, or it does not". A reconciliation job periodically compares what was sent with what was acknowledged. Figure 3. Scenario 3: the pipeline extended with a batch file exchange to an external partner, protected by a reconciliation job. Classification No usable timing signal at all. Any timeout you configure here is not a technical failure-detection mechanism. It is a business policy about how long you are willing to wait before escalating. Confusing the two is the central risk when testing this category of system. Edge Cases and Difficulties Timeouts cannot serve as failure detectors in the formal sense. A test asserting "if no response file arrives within X hours the system is broken" verifies a business escalation policy, not a technical correctness property. Writing it as if it were the latter produces tests that are correct in form and wrong in what they claim to verify.Four different failure states look identical from your side. The file was never picked up; the partner processed it, and a response is in transit; the partner processed it and silently rejected it; or the partner's batch job itself crashed. All four present as "no response file has appeared", and you cannot tell them apart without an out-of-band signal such as a phone call or a partner-side dashboard.Message identity is the only tool you have. With no timing signal, correctness has to be established entirely through content: unique batch and transaction IDs, checksums, and periodic reconciliation, rather than through any live handshake.The recovery path is often human-mediated. Someone emails the partner. The "system" under test therefore includes a human process step. The test strategy must mark where automated coverage stops and runbook verification begins instead of pretending the whole process is automatable.Reconciliation is the real correctness surface. It is not any single request and response, but the periodic comparison of what was sent against what was acknowledged, flagging discrepancies. That is closer to testing a batch ETL or audit job than a live API, and must be tested as one. What This Means for Testing Because no timeout can serve as a failure detector, testing here centers on the file contract (including malformed, duplicate, and missing files), on the reconciliation logic, and on ongoing monitoring in production. Much of it is a permanent operational activity rather than a pre-release one. How the Three Scenarios Compose into One System The three scenarios are not three different systems. They are three regimes that one real system passes through. Interesting bugs live at the boundaries between them. Consider a single order. It is placed on a phone with no signal (scenario 2), queued locally, and synced to the nearest region when connectivity returns. Inside that region, it flows through the gateway, Kafka, and core services with partially synchronous timing (scenario 1). The fulfillment step then leaves your infrastructure entirely, through an adapter and a file drop, and completes whenever the partner's batch job gets to it (scenario 3). Figure 4. The three regimes composed into one end-to-end order flow. Each boundary between zones is a place where the timing model changes. This composition has three practical consequences for test design. The end-to-end guarantee is only as strong as its weakest regime. The latency you can promise the customer is set by the scenario 3 segment, not by the fast core. The product must expose a "pending" state. Tests must verify that the pending state is reachable, stable, and correctly resolved by the reconciliation path.Every boundary needs its own contract test. The handoff from device to region (idempotent replay of queued actions), from Kafka to the adapter (exactly-once processing semantics on the file write), and from partner response back to the pipeline (reconciliation and dedupe) are each a place where the model changes and the assertions must change with it.A single end-to-end test cannot cover the whole path. An end-to-end test that waits synchronously for "order confirmed" is a valid test of scenario 1 only. Across the full path, use a correlation ID propagated through every hop, assert on intermediate observable states, and accept that the terminal state can only be verified by the reconciliation mechanism, not by waiting. 3.5 Summary of the three scenarios Scenario 1: Partially synchronous Scenario 2: Async, weak time Scenario 3: Async, no time Setting Single-region microservices Multi-region plus offline mobile Batch or EDI partner integration Is a timeout a valid failure signal? Yes, if calibrated to the real latency distribution Locally usable, untrustworthy across boundaries No; any timeout is a business escalation policy Primary correctness tool Calibrated timeouts and circuit breakers Logical or vector clocks, conflict resolution Message identity and periodic reconciliation Hardest bug class Retry storms and cascading failure under load plus degradation Silent misordering from untrusted clocks Indistinguishable failure states with no out-of-band signal Wrapping Up A test strategy starts from a map: the components, the networks between them, and who owns which state, drawn at the coarsest grain that still lets you inject the fault you care about. This part mapped the system and classified three regimes it can fall into: partially synchronous, asynchronous with a weak notion of time, and asynchronous with no notion of time at all. That classification is the lens for everything that follows. How asynchronous a connection is determines which tests are valid. In the partially synchronous core region, calibrated timeouts are legitimate. Interesting bugs can appear when load and degradation arrive together. With a weak notion of time, client timestamps cannot be trusted, so we need logical ordering and idempotent replay. With no notion of time, a timeout is a business policy rather than a failure detector. Message identity and reconciliation are useful here. In practice, systems pass through all three regimes, so every boundary needs its own contract tests. No single end-to-end test covers the whole path. Part 2 picks up directly from here: it takes the components and networks mapped above and walks through the full taxonomy of what can actually fail in each of them. Component by component and network hop by network hop, it then looks at how to test failure detection and mitigation as properties in their own right.
Many quality engineering teams have started using agentic AI testing. They connect an agent to their app and give it a human-readable task like “Test the checkout flow and tell me if anything is broken.” And it often works great! A few minutes later, they have their answer. However, if they send that same request tomorrow, even with the same exact code set, that “great” answer might just change. This happens because the agent takes an alternate route through checkout. Or tests different details. Or uses different test data. Regardless of the why, the test just isn’t consistent. In fact, in a recent experiment, Slack’s engineering team showed that only about 20% of runs follow the exact same sequence of actions … even with the same detailed prompts! This is a problem for regression tests and audits, or anything else that needs to be consistent. If a regression test fails, you need to know it’s the application that changed, not your test. In this article, I’ll show you how to use AI agent workspaces to make agentic quality engineering more repeatable. What Is an AI Agent Workspace? An AI agent workspace is a single controlled place for building and running your test agents. It’s a platform where you design your AI test agents, build the workflows they follow, then run and monitor those workflows. Workspaces help control agent sprawl (prompts and agents scattered across tools and teams) and give you a single location for governance and maintenance. Workspaces are typically built from three components: A workflow that defines the steps.An AI agent that executes each step.Tools that connect agents to services like Jira, GitHub, or your test management system. Two key features of workspaces include: Approval gates that pause the workflow, allowing a human to review output before continuing on.Saved workflows that run the same defined steps every time, using the same instructions and same toolset. Setting Up an AI Agent Workspace for Regression Testing Let’s look at how you can do this in the real world. First, as with many solutions, you can build your own AI agent workspace or buy one off the shelf. Building Your Own Workspace If you want to build it yourself, take a look at LangGraph. LangGraph is an open-source framework that gives you the needed workflow structure and human-in-the-loop checks. With LangGraph, you’ll need to custom-build some of the functionality yourself, especially around the testing itself. At a high level, you'll need to: Write the workflow in code (including handling failures)Generate the testsWrite the logic for checking for duplicate testsAnd wire in your test tools. Once it’s running, you’ll need to maintain it, including keeping a run history for audits and updating things when your tools or models change. Building makes the most sense if you need full control over your models and where your data lives, or if for some reason you can’t use the test tools a commercial workspace is built around. Using an Off-the-Shelf Workspace Let’s look in detail at an example of perhaps the more common choice, integrating off-the-shelf software. For our example, we’ll use Tricentis AI Workspace. It fits well into our definition as it uses the three key components: workflows, agents, and toolsets. In this case, a toolset can connect to other products such as Tosca Cloud, qTest, and NeoLoad, or popular outside services like Jira and GitHub. To start, we’ll use the workflow assistant. We’ll tell it about our goals, inputs, and branching. Let’s use a common real-world case: a checkout regression suite. In our example, Story PROMO-214 just came in and adds promo codes to the checkout. We want to create new tests for whatever isn’t yet covered, plus make any updates to existing tests. We definitely don’t want duplicates. And we don’t want anything saved until a human validates everything. First, let’s describe the workflow to the AI assistant. We might start with something like this: Shell Create a workflow with three inputs: a Jira ticket ID, a qTest project name, and a qTest module name. Read the requirements and acceptance criteria from the ticket. Generate test cases with the Tricentis Quality Agent. Wait for the generation job to finish, and end the workflow if it fails. Compare the generated test cases with the existing test cases in the qTest module, and propose which ones to create, update, or delete. Don’t change anything in qTest until a person approves it. From here, the assistant may ask a few follow-up questions. It then creates any agents the workflow needs, connects the steps, and activates the workflow. Once it’s built, we can go back into the agents it created or reused and refine them. Making the Workflow Repeatable Here’s where it can get a little tricky. The workflow above defines the steps, but each step still runs using an LLM, so the same step can produce different output on different runs. The prompt we just wrote is only used to build the workflow. On each run, every step follows its own agent’s settings and instructions, so that’s where we tighten things up. Tools. Give each agent just the tools it needs. Our Jira reader, for example, just gets read access to Jira. The step that compares test cases doesn’t need any tools at all. And only the last step is allowed write access to qTest. When you set up each agent, you pick its tools from a list.Temperature. This controls how random, or creative, the model is allowed to be. In AI Workspace, temperature runs from 0.0 to 2.0. Some newer models don’t accept a temperature setting at all, so check yours. But keep in mind that even a temperature of 0 doesn’t guarantee identical output! You’ll find Temperature under each agent’s Advanced settings.More specific instructions. Clearly spell out the rules and output format in each agent’s instructions. This way the model has less room for interpretation. For example, here’s what I’d give the comparison agent: Shell Compare the generated test cases with the existing qTest test cases from the earlier steps. Score each match on keyword overlap, test functionality, and test step content. Exclude matches below 70%. Return JSON with one entry per test case: the action (create, update, or delete), the matching qTest case ID (if any), and a one-line reason. Never propose a new test case without a requirement behind it. Fail if a test requirement is missing. To add approval gates, open the relevant workflow step, select Enable approval gate, and turn on Require approval. When we run the new workflow, we enter a ticket ID, a qTest project, and a module. The workflow reads the ticket, generates the tests, compares them with what’s already in qTest, and waits for a person to approve the proposed changes. This is where repeatability comes from. The workflow creates tests the same way each time, and once they’re saved in qTest, they follow the same exact steps on every run, whether a tester runs them or you automate them in Tosca. A workflow can kick off manually, on a schedule, or with an event. For PROMO-214, we want the workflow to start when the story moves to Ready for QA. Jira Automation can watch for that status change and send a POST request to the workflow’s webhook URL. And what about audits for when things go wrong? Workflow runs are tracked, so each one appears in the run history, and you can export it. Using Templates AI Workspace comes with templates that can help you get started: “Find and update relevant test cases.” Starts by reading a Jira ticket. Then it generates tests, checks them against your existing qTest cases, and updates qTest. There are three approval gates along the way, including a final one before it changes your qTest project.“Test coverage analyzer.” Compares requirements with qTest cases and reports an estimated coverage percentage.“Get your test requirements ready.” Runs before testing starts. It flags vague or missing acceptance criteria in your requirements and drafts questions for whoever wrote them. Here’s how “Find and update relevant test cases” looks. It’s very close to what we just asked the assistant to build. If we started from this template for PROMO-214, I’d keep all three of its approval gates: On the generated tests. Does a 10% code really take $10 off a $100 cart?On the change proposal. A test lead checks proposed updates/deletes, watching for a test, for example, that’s marked for deletion but is still needed.Before the write to qTest. A final review before anything changes. What Still Needs a Human in Agentic Quality Engineering You could save your workflow here and start testing. But I wouldn’t. A bad decision saved into a workflow … is a bad decision that repeats on every single run. So I like to keep a few steps with the humans. First, human approval gates are always a good idea just as a sanity check before an agent’s output reaches your test repository, or anywhere else that’s hard to clean up. Humans also should decide if a test is checking the right thing. Distinguishing correct behavior from incorrect behavior is what researchers call the oracle problem, and it’s been a bottleneck in test automation for a long time. One recent study of LLM-generated unit test assertions across 24 Java projects, with the code in the prompt, found that LLM-based test generation approaches “mainly capture the actual program behavior.” In other words, an LLM that reads your code tends to treat whatever the code actually does as correct. Finally, someone should check the actual coverage. A number in a coverage template is just an estimate of how well your tests match requirements. I’d have a person spot-check the matches before anyone reports an official coverage number. Conclusion My readers may recall my personal mission statement, which I feel can apply to any IT professional: “Focus your time on delivering features/functionality that extends the value of your intellectual property. Leverage frameworks, products, and services for everything else.” - J. Vester I don’t know anyone whose intellectual property became more valuable from retyping a test prompt and hoping for the same result. With an AI agent workspace, that job goes to a saved workflow, and your team gets to decide what to test and what the right result is. Have a really great day!
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.
The Job Nobody Was Watching We had a crucial job that watched our paid ad spend. It paused underperforming campaigns and moved their budget to the campaigns that performed better. Then the API key it used expired. Nothing was monitoring that cron job, so we assumed everything was running just fine. In the end, it cost us quite a bit of money: the underperforming ads were never paused, and they just kept running and collecting clicks. The annoying part is that everything around it looks fine. The web server answers requests. The database accepts connections. The status page is green. Meanwhile, the scheduled task that creates backups, imports orders, expires sessions, or generates invoices has quietly stopped. Cron fails by doing nothing. Sometimes the job never starts. Sometimes it starts, can't do its work, and tells nobody. There's no HTTP 500, because no HTTP request was involved. There may not even be a log line to grep for. That happens when the crontab is removed, the cron daemon stops, or the command can't be found. So you have to monitor for something that didn't happen. The job checks in. Silence is the alert. Why Your Existing Checks Miss It An HTTP uptime check answers a narrow question: can I connect to this URL and get an acceptable response? The homepage can return 200 while the weekday job scheduled for 02:17 has been dead for a week. An ICMP ping is narrower still. The kernel answers a ping even when cron is stopped, the application is broken, or the backup script has lost its credentials. Application health endpoints are useful, but they report what the running application says about itself. A healthy JSON response isn't proof that a separate scheduled task ran last night. All three checks ask whether something is there. A scheduled job needs the opposite question: did the job that should have run actually run? Silent jobs accumulate in predictable places: inherited crontabs, CMS plugins, forgotten Windows servers, framework schedulers, and scripts that one person configured years ago. The biggest risk lies in the type of cron job that only occasionally reports something to you. For instance, when everything is fine, the scheduled task does nothing. Otherwise, it sends you an email with an overview of the items that need fixing. It's quite common to receive nothing for weeks on end, and then an email with actionable items once every few weeks. If that email never comes, it looks like everything is fine and nothing needs your attention. But maybe the scheduled task was just broken. The Heartbeat Pattern A heartbeat works the other way around. The monitor doesn't poll the process, which may only exist for a few seconds. The process calls the monitor. Each job gets a unique URL. The job requests that URL after it finishes successfully. The receiver stores the timestamp and compares it with the expected schedule. If the next request does not arrive within the allowed window, it sends an alert. Plain Text scheduled job | | HTTP request after each run v unique ping URL | | timestamp compared with schedule v heartbeat monitor | | expected window passes without a ping v alert to the job owner Use one URL per job, not one URL per server. A message saying that server-12 missed a heartbeat still leaves you searching through its crontabs. A message naming nightly-database-backup gives you somewhere to start. The receiver doesn't need to be complicated. It can be a small self-hosted endpoint that records timestamps, or any heartbeat service. Step 1: The One-Line Version The smallest useful implementation is a successful command followed by a request: Plain Text 17 2 * * 1-5 /usr/local/bin/backup.sh && /usr/bin/curl -fsS -m 10 --retry 3 https://<monitor>/ping/<job-id> The && matters. It runs curl only if backup.sh exits with status zero. With ; instead, the ping goes out even when the backup fails. The monitor records a success for a backup that failed. The curl flags are there for unattended runs. -f treats HTTP error responses as failures. -sS hides the progress meter but keeps error messages. -m 10 limits the total request time. A slow receiver can't leave the job hanging. --retry 3 handles a short network interruption. Cron normally starts commands with a minimal environment. Its PATH may differ from the one in your interactive shell. Shell initialization files may never run. Use absolute paths for both the job and curl. Cron jobs don't always cleanly survive server migrations. If you blindly copy scheduled tasks from one server to a new one, but don't account for changed paths or directories, or even a different user that runs the code, the scheduled task may never execute correctly. The one-line version works, but it's incomplete. A failed job and a job that never started both stay silent until the monitoring window runs out. Step 2: Start and Finish Pings For a job that runs longer than a few seconds, send one request when it starts and another when it exits. This gives you a runtime. It also tells "never started" apart from "started but never finished." A Bash wrapper can do this without duplicating the exit handling: Shell #!/usr/bin/env bash set -Eeuo pipefail ping_url="https://<monitor>/ping/<job-id>" started_at=$(/usr/bin/date +%s) /usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true finish() { local exit_code=$? local finished_at local runtime finished_at=$(/usr/bin/date +%s) runtime=$((finished_at - started_at)) trap - EXIT set +e if (( exit_code == 0 )); then /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ "${ping_url}" || true else /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ "${ping_url}/fail" || true fi exit "${exit_code}" } trap finish EXIT /usr/local/bin/backup.sh The || true on the start request is deliberate. If the monitor is down, I still want the backup to run. A monitoring failure shouldn't turn into a backup failure. The EXIT trap keeps the job's original exit code and calculates its runtime. It sends the matching ping, then exits with that same code. If another start arrives before the earlier run finishes, you may have overlapping jobs, a stuck process, or a timeout elsewhere in the stack. Step 3: Fail Loudly, Not Late Without an explicit failure request, you only find out about a crash once the grace period expires. That is why the one-line && example is not enough for every job. A failed backup sends no ping. At first it looks the same as a backup that never ran. Send failures to /fail immediately. Include enough context for a first look: the exit code, the runtime, and a few lines of stderr. Shell #!/usr/bin/env bash set -Eeuo pipefail ping_url="https://<monitor>/ping/<job-id>" started_at=$(/usr/bin/date +%s) stderr_file=$(/usr/bin/mktemp) /usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true finish() { local exit_code=$? local finished_at local runtime local stderr_tail local endpoint finished_at=$(/usr/bin/date +%s) runtime=$((finished_at - started_at)) stderr_tail=$(/usr/bin/tail -n 20 "${stderr_file}") endpoint="${ping_url}" if (( exit_code != 0 )); then endpoint="${ping_url}/fail" fi trap - EXIT set +e /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ --data-urlencode "stderr=${stderr_tail}" \ "${endpoint}" || true /usr/bin/rm -f "${stderr_file}" exit "${exit_code}" } trap finish EXIT /usr/local/bin/backup.sh 2>"${stderr_file}" "The backup was missed" is vague. "The job ran for 12 minutes and exited 137" is actionable. Exit code 137 is 128 plus 9, meaning the process received SIGKILL. The out-of-memory killer is a common cause. Check memory pressure first. It's not uncommon for a PHP scheduled task to run into a segfault if you're running an older PHP version. Without actionable monitoring, those errors simply disappear. They don't even end up in your PHP error log, because PHP crashed before it could write one. The wrapper above still catches it: the failure ping arrives with exit code 139, which is 128 plus 11, SIGSEGV. Don't ship the whole log. The last 20 lines are usually enough for a first clue. The full log can stay on the host. Step 4: Describing the Schedule Honestly There are two common scheduling models. The first expects a check-in at least once every N minutes. The second evaluates an actual cron expression. Intervals work for jobs that run continuously or at a fixed frequency. They don't fit calendar schedules. A job scheduled for 02:17 from Monday through Friday will look late every Saturday if the receiver expects a request every 24 hours. For calendar-based jobs, give the monitor the same cron expression the scheduler uses. Give it the time zone too. A cron expression without a time zone is ambiguous, especially when the server, application, and monitoring receiver use different defaults. Daylight saving time makes this worse. In most of Europe, the clocks jump from 02:00 to 03:00 in spring. A 02:17 run doesn't exist that day. In autumn, the hour from 02:00 to 03:00 happens twice. What cron does with that depends on the implementation. Your monitor has to agree with it. Leap seconds used to cause issues too. Today, systems mostly handle them fine. But more than a decade ago, I remember that the occasional server crash during a leap second was not uncommon. The server would often reboot on its own, but whatever was scheduled to run during the reboot never executed. Cron doesn't catch up on missed runs, so only a heartbeat would have told you. A grace period sets how late a check-in may be before the job counts as missed. It must cover both late starts and slow runs. A backup that normally takes 90 seconds but sometimes needs six minutes should not alert at the two-minute mark. Set the grace period from observed runtimes, with room for the slowest runs. Do not copy one value across every job. In our own system, we have jobs that do monthly reporting for our clients. Every client who opts in gets a monthly uptime report, sent either to the owner of the account or directly to their own clients. It's never quite clear how long generating those uptime reports will take: if a site had more downtime that month, its report takes longer. So that job has a quite generous grace period to account for fluctuations. It's also the type of job that keeps taking longer as more customers sign up and use the service, so the fluctuations might increase over time too. That's a grace period you have to revisit every now and then. Step 5: Send the Alert to Whoever Can Fix It A missed heartbeat that lands in a shared inbox nobody reads at 02:17 is the same as no heartbeat. Assign an owner to each job. Route the alert to the person or team that can inspect and restart it. The person responsible for a Windows task in one department may have no access to another team's framework scheduler. The alert should name the exact task, host, expected time, and last successful check-in. Make the name recognizable to the operator. Internal identifiers are fine for machines. job-7f3a doesn't tell a person what broke. Throttle repeats, too. One silent job should not produce an alert every minute. Notify when it becomes late. Repeat at an interval you choose, if needed. Resolve the incident when a valid check-in arrives. Beyond crontab The same pattern works anywhere a task can make an HTTP request: Windows Task Scheduler, queue workers, framework schedulers, deployment scripts, and one-off maintenance commands. A short PowerShell task can run a command, verify its exit status, and send the success heartbeat: PowerShell & "C:\Scripts\backup.exe" if ($LASTEXITCODE -ne 0) { throw "backup.exe exited with code $LASTEXITCODE" } Invoke-WebRequest ` -Uri "https://<monitor>/ping/<job-id>" ` -TimeoutSec 10 ` -UseBasicParsing This matters most on servers you inherited and don't fully control. Installing extra software there is often not an option. An HTTP request from the shell or runtime that's already on the box usually is. You still have to check three things: the request tool exists, credentials are handled safely, and outbound network access is allowed. If you're programming in PHP and you define your scheduled tasks in the framework, either in Symfony or in Laravel, the scheduler can send these pings for you. Laravel has start, success, and failure pings built in: PHP // routes/console.php use Illuminate\Support\Facades\Schedule; Schedule::command('backup:run') ->weekdays() ->at('02:17') ->timezone('Europe/Brussels') ->pingBefore('https://<monitor>/ping/<job-id>/start') ->pingOnSuccess('https://<monitor>/ping/<job-id>') ->pingOnFailure('https://<monitor>/ping/<job-id>/fail'); For Symfony, zenstruck/schedule-bundle has similar ping hooks. And there are open-source packages, like spatie/laravel-schedule-monitor, that automatically register all your scheduled tasks with your heartbeat monitor and keep them in sync. That doesn't even need a single extra line of code in your task definitions. What a Heartbeat Can't Tell You A heartbeat proves the job got far enough to send its check-in. It doesn't prove the backup can be restored. It doesn't prove the report has the right rows, or that the import matched your business rules. A command can exit zero after producing an empty file, skipping half its input, or writing corrupt output. Pair the heartbeat with validation that fits the job. Restore backups on a schedule and test the restored data. Check that an export is non-empty and has a plausible row count. Verify a checksum after transferring a file. Make an import exit non-zero when required records are missing. Validation has to change the job's exit status. If the script detects bad output but still exits zero, the heartbeat reports a success. If you're just getting started, you don't need a full validation suite on day one. Differentiating between what you consider the good outcome and the bad outcome, regardless of what that bad outcome is, is already powerful: it alerts you to the problem and lets you investigate deeper. Once that works, add metadata to the failure ping, like in Step 3, so it carries the exact failure message: why the task didn't do its work, either because its data was invalid or because an exception was thrown midway. Rollout Checklist Start with an inventory. Check every user's crontab on each host, system-wide cron directories, Windows Task Scheduler, framework schedulers, queue systems, and CI schedules. Undocumented jobs are the ones most likely to stay silent. For each job: Assign one unique ping URL.Use &&, not ;, for the basic success-only form.Put timeouts and retries on every curl request.Use absolute paths in crontab.After a server migration, check the paths and the user that runs each job.Add start, finish, and failure requests for jobs that take more than a few seconds.Configure the real cron expression and the time zone the scheduler actually uses.Set the grace period from actual runtime observations.Assign an owner who can investigate the alert. Test failure as well as success. Temporarily use a command that exits non-zero and confirm that the failure path runs. Then disable the schedule on purpose and check that an alert arrives after the expected window. Closing I've seen scheduled tasks fail in spectacular ways: from an expired SSL certificate on a remote API that made the task's curl call fail, all the way to segfaults, race conditions, time zone issues, faulty deploys — you name it. It's easy to fall into the trap of thinking that a scheduled task, once defined, will keep running forever. But chances are neither your code nor your infrastructure is static. It moves; it evolves. You iterate based on market demand; you change the application. You have to monitor all these moving pieces, and scheduled tasks are definitely one of them.
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.
Every new cluster brings the same chore: copy the registry password into every namespace that pulls private images, and repeat it when the password rotates. Clusters are created dynamically, so the chore never ends, and each copy is one more place where the password can expire or leak. Kubernetes 1.34+ offers a way out: the kubelet can hand a credential provider plugin the ServiceAccount token of the pod whose image it is pulling, and the plugin swaps it at the registry for short-lived, read-only credentials. A ServiceAccount token is issued for a specific pod for a limited time and does not sit in any manifest. The registry decides which tokens it trusts. That is closer to zero trust: the workload holds no long-lived secret that could be stolen and used from somewhere else. The scheme works, but when it fails, the cause is hard to find. The pod goes into ImagePullBackOff, and the events show only a generic registry answer: failed to resolve reference ... unexpected status from HEAD request. The real cause is written by the kubelet and appears only in its log on the node: Plain Text ak-kubelet-provider: https://ak.test: 401 CI JWT did not match any identity mapping That line does not appear on its own: the kubelet, the nodes' permissions, and the registry all have to be configured first. The examples use a plugin I wrote and the open-source Artifact Keeper registry, and they all come from my test cluster. What the Registry Has to Do The scheme needs a registry that accepts Kubernetes ServiceAccount tokens, which are OIDC tokens signed by the cluster, and issues short-lived credentials in exchange. Any registry that can verify the cluster's OIDC tokens and issue such credentials fits. The examples below use Artifact Keeper 1.11, which has this exchange built in. How the kubelet Passes the ServiceAccount Token to the Plugin The kubelet can obtain image credentials from an external executable, called an image credential provider. It runs on every node. The kubelet writes a JSON request with the image name to its stdin and reads a username, a password, and a cache duration from its stdout. Kubernetes 1.34 added the ServiceAccount token of the pod being started to that request (KEP-4412, the tokenAttributes field in the config). Before that, a plugin saw only the image name and could rely only on the node's identity. Now it knows which pod asks for the image and can exchange the token for access granted to that ServiceAccount. The config for this plugin looks like this: YAML apiVersion: kubelet.config.k8s.io/v1 kind: CredentialProviderConfig providers: - name: ak-kubelet-provider matchImages: ["ak.test"] defaultCacheDuration: "5m" apiVersion: credentialprovider.kubelet.k8s.io/v1 args: - --url=https://ak.test tokenAttributes: serviceAccountTokenAudience: artifact-keeper cacheType: ServiceAccount requireServiceAccount: true serviceAccountTokenAudience says who the token is issued for. It needs a dedicated value that differs from the API server's audience. With the API server's audience, the registry would accept the token of any pod, and the token the plugin sends to the registry would also be valid against the API server. Artifact Keeper refuses to create such a provider and answers 400. The whole exchange is shown in the diagram below. The image is not on the node yet, so the kubelet calls the plugin. The pod in team gets access because the registry has a mapping for the namespace team, a rule that admits ServiceAccounts from it. The plugin returns a cacheDuration to the kubelet, equal to the lifetime of the issued token minus 60 seconds. With cacheType: ServiceAccount the kubelet caches credentials per ServiceAccount. A second pod of the same ServiceAccount takes them from the cache, while a pod of another ServiceAccount calls the plugin itself. What the Cluster Needs Besides the Plugin The plugin works only together with a few cluster settings. Without them, the image does not arrive, and the cause is hard to find. Nodes must be allowed to request tokens for the audience. Since Kubernetes 1.33, ServiceAccountNodeAudienceRestriction is in effect. The API server does not issue a node a token with an audience that is not in the pod's projected volumes unless the node has been explicitly allowed. Without that permission, the kubelet logs is not authorized to request tokens for this audience and pulls the image without credentials. The pod gets a generic denial, as if there were no plugin at all. The permission is granted by a ClusterRole bound to the group system:nodes: YAML rules: - apiGroups: [""] resources: ["artifact-keeper"] verbs: ["request-serviceaccounts-token-audience"] resources here is the audience itself. If nodes have no permission for the audience, the plugin does not run at all: the registry receives neither a request nor an error, and the events show a generic denial. kubelet flags. You need --image-credential-provider-config and --image-credential-provider-bin-dir. My kind config with kubeadmConfigPatches did not apply them, so I appended the flags to /var/lib/kubelet/kubeadm-flags.env on the node and restarted the kubelet. If the plugin is not called at all, the kubelet log has no line from ak-kubelet-provider. Then check matchImages (the image host must match) and the audience permission from the previous point. The Registry Swaps the Token for Read-Only Access To accept ServiceAccount tokens and issue credentials in exchange, Artifact Keeper 1.11 has a CI OIDC provider of type kubernetes. First I create the provider. On my test setup, the registry runs inside the same kind cluster: I give it the signing keys statically, and it does not have to reach the API server's discovery endpoint: Shell kubectl get --raw /openid/v1/jwks > jwks.json jq -n --slurpfile jwks jwks.json '{ name: "prod-cluster", provider_type: "kubernetes", issuer_url: "https://kubernetes.default.svc.cluster.local", audience: "artifact-keeper", key_source: "static", static_jwks: $jwks[0]}' | curl -X POST https://ak.test/api/v1/admin/ci-oidc \ -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" -d @- Then I create a mapping that defines which ServiceAccounts get access and binds them to a group with read permission: Shell curl -X POST https://ak.test/api/v1/admin/ci-oidc/$PROVIDER_ID/mappings \ -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"name":"team-ns","priority":10, "claim_filters":{"/kubernetes.io/namespace":"team"}, "group_binding_ids":["'$GROUP_ID'"]}' A key that starts with / is a JSON Pointer into the token's claims. This single namespace filter admits every ServiceAccount in team. The match is exact: team does not admit team-sandbox. All ServiceAccounts admitted by one mapping share one registry account, in my case ci-1007c2257aba. You can tell them apart in the registry log, which records the namespace, ServiceAccount, pod and node of every exchange. A Foreign Namespace Is Denied, a Mapped One Pulls the Image I started a kind 1.34.3 cluster and installed Artifact Keeper 1.11.1 inside it. I built the plugin from main for arm64 musl. Results: Check Result Pod in team with ServiceAccount app Image pulled on the first attempt, no imagePullSecrets Second ServiceAccount other in team, same mapping Pulled, the exchange returned 200 Pod in namespace outsider, which has no mapping ImagePullBackOff, the kubelet log shows 401 CI JWT did not match any identity mapping, as in the introduction push with the issued token denied: Token does not have required scope: write:artifacts, on both blobs and the manifest Create an API token with this token 403 Create a provider with the API server's audience 400 The token the plugin receives can only read. The registry limits it by provider type and does not consult the group's permissions: even if the group has write access, this token writes nothing. An Image Already on the Node Hides the Denial The outsider check fooled me at first. I started a pod in the foreign namespace and it came up. The reason: the image was already on the node after the first pod. The kubelet does not pull an image it already has, so the plugin is never reached. The same pod from a foreign namespace either starts or fails, depending on imagePullPolicy and on whether the image is already on the node. In the first case, the registry never hears about it. To test a denial, you need imagePullPolicy: Always or an image that is not on the node. Until you do that, any check of the kind "a foreign ServiceAccount must not get in" passes green. The Plugin: One Rust Binary, No Token in the Logs It is a single static Rust binary of about 1.7 MB. The HTTP client is ureq with rustls, and there is no async runtime. It builds for x86_64 and aarch64 musl and is signed with cosign. There is no async runtime on purpose: the process lives for tens of milliseconds and needs a single request. The binary runs as root on every node, so it follows a few rules, each covered by a test: The token never reaches the logs at any level, and if the registry echoes it in an error message, the plugin replaces it with [REDACTED];http:// is rejected before any request is sent, so the token cannot travel over an open channel;Redirects are not followed, so the token cannot be sent to another address;The whole exchange runs under a single timeout, 10 seconds by default. On failure, the plugin writes one line to stderr and exits with code 1. The kubelet records it in its own log and pulls the image without credentials. That is why pod events show only a generic denial, while the details sit on the node: journalctl -u kubelet | grep ak-kubelet-provider. EKS, GKE and AKS: A Recipe Exists, Real Clusters Have Not Been Tried On these platforms, you cannot set kubelet flags directly. The schemes below are tested in parts and on kind, so treat them as a working plan without guarantees. EKS (Amazon Linux 2023). nodeadm writes a config.json with a single provider, ecr-credential-provider. A script in the user data copies that file and adds an entry for the plugin. The script passes the file with the added entry to the kubelet as a second --image-credential-provider-config flag. Of two identical flags, the kubelet takes the last one, so it reads that file, and the ECR entry stays in it: EKS system images still come from ECR. This does not work on Bottlerocket, EKS Auto Mode, or Fargate. GKE Standard and AKS. Neither Google nor Microsoft lets you add a plugin through their API. For them, the repository has a privileged DaemonSet: it finds the provider config on the kubelet's command line, adds the plugin there, and restarts the kubelet. If the kubelet does not come back after the restart, the DaemonSet restores the previous config. The vendors do not support this approach and may break it with a node image update. The DaemonSet pod runs as root on every node, so only cluster administrators should be able to change its ConfigMap. 19 ms per Call, and a Cache That Spares Repeat Exchanges The measurements were taken on a single kind node (a laptop, with the registry in the same cluster): network latency is close to zero. The numbers show the cost of the plugin itself, not of your network. One plugin call takes about 19 ms including process start and the TLS handshake: 100 sequential calls took 1.9 s.200 calls, 20 in parallel, finished in 1.1 s with no errors.The registry token's lifetime in my setup is 30 minutes. For a one-hour ServiceAccount token, the plugin returned a cacheDuration of 1740 s: 30 minutes minus a 60-second margin.20 pods of one ServiceAccount that had not yet been seen on the node produced 2 exchanges instead of 20. Most likely the second exchange happened before the cache was filled. cacheDuration follows the shorter of the two tokens: with a 10-minute ServiceAccount token, the plugin returned 539 s, with a one-hour token 1740 s. What My Tests Do Not Cover Real EKS, GKE, and AKS clusters. The only real run is on kind.Kubernetes releases newer than 1.34.3. All tests ran on 1.34.3, the minimum version the plugin supports.The registry mode in which it fetches the cluster's signing keys itself (discovery). I used static keys.Load on the registry itself: how it copes with hundreds of nodes asking for tokens at the same time. Code and Further Reading The kubelet side is described in the Kubernetes documentation on kubelet credential providers and in KEP-4412. The example plugin, the installation recipes, and all configs from this article are in the artifact-keeper-kubelet-provider repository. If you try the recipes on EKS, GKE, or AKS, a note about what worked and what did not is welcome.