DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

DZone Spotlight

Tuesday, November 24 View All Articles »
How We Cut DynamoDB Ingestion Reads With an S3 Hash Pre-Filter

How We Cut DynamoDB Ingestion Reads With an S3 Hash Pre-Filter

By Navaprasad Maram
The Setup Our team runs a customer data platform: a single source of truth for customer profile data, serving a high-volume read application programming interface (API) and ingesting changes from hundreds of upstream systems. The storage layer is Amazon DynamoDB in an entity–attribute–value (EAV) layout: the partition key is the entity ID, the sort key is the attribute name, and each item holds an attribute value plus a source version—the upstream update timestamp carried on that event. Ingestion runs on Apache Flink — hundreds of pipelines, one per source. Some sources stream changes continuously; others are batch, publishing once a day. Because Flink handles both modes, all of them share one codebase, with JOLT (a JSON-to-JSON transformation library) handling per-source transformations declaratively, so onboarding a new source is mostly configuration. Each pipeline does a read-before-write for every incoming record: fetch the entity's stored attributes, compare versions, and discard the event if its version is older than what's stored — that's our idempotency guard. If the version is newer but the values haven't changed, discard anyway, because a write that changes nothing is a write capacity unit spent on nothing. That last rule is the irony this article is about. The check we built to save write costs is itself a read. And reads, it turned out, were where the money was going. The Problem: The Reads Weren't Coming From Where We Thought When DynamoDB read costs climbed to the point of demanding attention, everyone's first suspect was the obvious one: the read API, the thing serving thousands of requests per second. We dug through the access logs expecting to find a hot consumer or an inefficient query pattern. The API wasn't the problem. The ingestion was. Every one of those hundreds of pipelines was faithfully doing its read-before-write on every record it received — and the volume of records they received had nothing to do with how much data was actually changing. The reason was a design principle on the batch side. Batch sources build daily events from a data lake, and the natural way to do that is to emit the complete entity—a Person event carries firstName, lastName, phoneNumber, everything—for every entity, every day. A full snapshot, not a changelog. From the source's perspective, that's simple and robust. From ours, each batch snapshot triggered a DynamoDB fetch of the stored attributes, even when none of the attributes we had onboarded had actually changed. Our analysis showed how concentrated the activity was: around 90% of batch events carried changes to only about 10% of the source data. That is not the same as saying 90% of DynamoDB reads were avoidable. For our filter, the relevant question was narrower: did any of the attributes we actually onboarded change? That distinction matters when estimating how many read-before-write checks can safely be skipped. The Thought Process: Three Options, Two Rejected Option 1 — fix it upstream. The cleanest fix is for sources to publish only what changed, so we asked. Some were willing. But even a willing source couldn't fully solve it: a source entity has N attributes, and we typically onboard only a subset. The source can't tailor its change detection to our subset — so when an attribute we never onboarded changes, they still (correctly, from their view) publish an event, and we still pay to discover it's a no-op for us. Upstream cooperation helped at the margins; it couldn't be the answer. The filter had to live on our side, and it had to be aware of what we onboarded, not what the source produced. Option 2 — keep the filter state in Flink. Flink has first-class managed state, checkpoints, and savepoints. A per-entity fingerprint in managed state could avoid a remote lookup. We rejected that option for reasons specific to our operating model—not because Flink state is generally unreliable. Across hundreds of jobs, we had experienced offset resets and cases where fingerprint state was lost or had to be rebuilt. That didn't corrupt writes, but it silently returned affected pipelines to full DynamoDB read volume until their cache warmed up. We wanted the cost optimization to survive each job's lifecycle without special restoration steps. Option 3 — externalize the fingerprint to S3. For each daily batch event, compute a hash over only the attributes we've onboarded. Look up the previously stored fingerprint in S3, keyed by entity name and ID. A match can allow the pipeline to avoid the DynamoDB read; a missing fingerprint or mismatch takes the original read-before-write path. This is a batch-only pre-filter, not a replacement for the downstream version and value checks. Its safety depends on how the fingerprint is maintained relative to committed DynamoDB state. There is more to “hash the attributes” than choosing a digest function. The input needs a stable field order and value encoding, with an explicit distinction between a missing field and a null value. The projection must include every onboarded attribute and exclude source-only fields. Otherwise, equivalent events create unnecessary mismatches—or a relevant change is left out of the comparison entirely. A collision-resistant hash helps with accidental collisions, but it can't fix an inconsistent projection. Why S3, of All Things Using S3 for per-entity lookups sounds backward until you look at what the daily batch workload actually needs: It's a batch. These pipelines process daily snapshots; nobody is waiting for a sub-millisecond answer. S3 GET latency isn't free, and request volume still affects total runtime, but this workload has more room to make that trade-off than a real-time API. We left streaming pipelines untouched.It's cheap where it counts. S3 GET requests can be substantially cheaper than the DynamoDB capacity needed to fetch an entire EAV entity in this workload. But the comparison includes S3 PUTs, object storage, GET rates, and batch duration — not just one request price. The filter pays off only when the avoided DynamoDB reads outweigh those added costs.It's independent of job state. An S3 fingerprint persists across Flink restarts, redeployments, offset resets, and rescaling. That separated the cost optimization from the operational lifecycle of hundreds of individual jobs.Failure handling matters. A missing or unreadable hash can fall through to the usual DynamoDB check. A stale hash is not automatically harmless: if it matches a later event after DynamoDB's value has changed, the pipeline could discard a valid update. The safe invariant is that a fingerprint used to skip a read must correspond to a confirmed committed projection, with explicit handling for retry, replay, concurrent updates, and reconciliation. A collision-resistant hash makes accidental collisions unlikely; it does not solve S3–DynamoDB synchronization errors. The result was a substantial reduction in ingestion read pressure. A qualifying fingerprint match bypasses the DynamoDB fetch altogether, so read demand no longer has to follow every daily snapshot a source publishes. The source-data 90/10 pattern motivated the change, but it is not a measured 90% reduction in read requests or dollars saved; those outcomes depend on the actual match rate and the additional S3 request and storage costs. To evaluate the economics of this pattern, we'd compare the actual fingerprint match rate, DynamoDB read requests or consumed read capacity, S3 GET/PUT and storage charges, and total batch duration across similar daily runs. Those numbers — not the raw 90/10 input skew — determine the net benefit. The batch-only read path, before and after the pre-filter: pathwhat happens in batch ingestion Before Daily snapshot → DynamoDB entity read → version/value comparison → write or discard. After: fingerprint lookup Daily snapshot → project onboarded attributes → deterministic hash → look up S3 fingerprint. Trusted match Skip the DynamoDB read, provided the fingerprint represents confirmed committed state. Miss or mismatch Run the normal DynamoDB read-before-write checks; keep the fingerprint aligned with confirmed state. The Takeaway Three lessons we'd offer anyone running read-heavy ingestion against a pay-per-request store: Follow the bill to the actual caller. Our read costs looked like an API problem because the API was the visible reader. The logs said otherwise. Cost work that starts from assumptions optimizes the wrong component with great precision. A guard has a cost of its own. Read-before-write is a sensible idempotency and no-op-suppression pattern, but every guard evaluation is billed. When batch sources republish largely unchanged data for the attributes you actually store, the guard becomes much of the workload. The answer isn't to remove the guard; it's to put a cheaper, correctly synchronized filter in front of it—in our case, a hash over onboarded attributes, which no upstream source could tailor to our subset. Match the store to the workload's tolerance, not to reflex. S3 as a key-value lookup violates every low-latency instinct — and was exactly right for a batch path that tolerates latency and rewards durability and cost. The cheapest read is the one you never make; the second cheapest is the one you make against the cheapest store that's good enough. More
Five Common Time-Series Queries Made Simple With Enterprise Java

Five Common Time-Series Queries Made Simple With Enterprise Java

By Otavio Santana DZone Core CORE
Enterprise applications have typically stored only the current state of information, such as account balances, order statuses, or inventory quantities. However, monitoring changes to these values over time is also essential. As businesses increasingly depend on real-time analytics, observability, and continuous data processing, time-series databases provide a specialized solution for storing and querying time-based data. Java developers and software architects should not have to learn a new query language for each database when working with temporal data. Eclipse JNoSQL introduces five new operations in its TimeSeries fluent API, making it easier to retrieve historical data, recent activity, and specific time ranges using familiar Java patterns. This article discusses the significance of time-series data for enterprise applications and demonstrates how these features simplify temporal queries while supporting polyglot persistence. Why Time-Series Data Matters for Enterprise Applications Traditional databases manage transactional information well, but temporal workloads require different access patterns. For example, a banking application may store an account balance. Knowing a customer has €5,000 is helpful, but tracking how that balance changes throughout the day can reveal unusual activity, spending patterns, or potential fraud. Rather than retrieving a single state, the application must analyze a sequence of observations over time. This is the key distinction of time-series data: time is central to how information is stored, retrieved, and analyzed. Time-series databases are built for frequent ingestion, chronological retrieval, and time-based aggregations, though their features and trade-offs differ by implementation. These features make time-series databases valuable in various enterprise scenarios: Financial services: Analyze transaction histories, market fluctuations, and unusual activity within specific time windows.Application observability: Monitor response times, error rates, and resource consumption to investigate performance degradation or incidents.E-commerce: Track purchasing activity, demand fluctuations, and inventory movements to identify trends and seasonal behavior.IoT and industrial systems: Collect temperature, pressure, energy consumption, and equipment measurements to support monitoring and predictive maintenance.Business analytics: Compare revenue, customer engagement, and operational performance across different periods. Returning to the financial example, an application may need to retrieve the three most recent transactions, identify the earliest activity, review transactions since a specific timestamp, or analyze all activity from the past 24 hours. While these are common business needs, implementing them across different databases often requires unique query syntax and database-specific APIs. Traditional relational databases can handle temporal queries, especially with proper indexing and partitioning. The choice of architecture depends on ingestion volume, retention needs, query patterns, and operational costs. Specialized time-series databases are most beneficial when temporal workloads are the primary requirement. For enterprise Java developers, another challenge with databases like InfluxDB, QuestDB, and Apache IoTDB, as each offers distinct query capabilities and integration models. Eclipse JNoSQL addresses this by extending its fluent API with five temporal operations: latest(), earliest(), since(), until(), and last(). Let’s examine how these methods enable common temporal queries directly in Java. Working With Time-Series Data in Eclipse JNoSQL Eclipse JNoSQL extends its polyglot persistence to time-series databases, enabling Java developers to manage temporal data with familiar persistence patterns. The project currently integrates with InfluxDB, QuestDB, and Apache IoTDB. These databases offer distinct features, such as time-based analytics, high-throughput ingestion, and industrial telemetry. Eclipse JNoSQL delivers a consistent Java programming model across them. This integration builds on three complementary Jakarta specifications: Jakarta NoSQL: Provides entity mapping, annotations, and template-based persistence.Jakarta Data: Introduces repository abstractions, reducing boilerplate for common persistence operations.Jakarta Query: Defines a common query foundation across Jakarta persistence technologies, with Eclipse JNoSQL integration under development. For time-series operations, Eclipse JNoSQL introduces TimeSeriesTemplate, a specialized version of Jakarta NoSQL’s Template interface. It maintains standard persistence operations and adds features for temporal queries. Mapping Temporal Data Consider a financial application that tracks account transactions over time. Rather than storing only the current balance, each transaction is represented as an individual observation: Java @Entity public class AccountTransaction { @Id private Instant id; @Column private String account; @Column private BigDecimal amount; @Column private String currency; @Column private TransactionStatus status; The mapping uses standard Jakarta NoSQL annotations, but the identifier must represent time. In this example, Instant indicates when the transaction occurred and serves as the temporal reference for queries. Unlike conventional entity identifiers that use strings, UUIDs, or numbers, the time-series fluent API requires a supported temporal type for the @Id field. Supported types include Instant, LocalDateTime, LocalDate, OffsetDateTime, and ZonedDateTime. This enables the API to interpret operations chronologically without requiring developers to specify a timestamp field in each query. Timestamps are not guaranteed to be unique across all observations. Applications handling concurrent events should consider timestamp precision, potential collisions, and the database provider's identity model. Once the entity is mapped, you can persist an observation using TimeSeriesTemplate: Java @Inject TimeSeriesTemplate template; template.insert(transaction); For standard operations, developers can also use Jakarta Data repositories: Java @Repository public interface AccountTransactionRepository extends BasicRepository<AccountTransaction, Instant> { List<AccountTransaction> findByAccountOrderByIdDesc( String account, Limit limit); } Both approaches complement each other: repositories simplify common persistence tasks, while TimeSeriesTemplate provide specialized temporal queries. However, enterprise applications often need more than basic insert and retrieve operations. Common questions include: What are the latest transactions? What happened during a specific period? Which observations occurred within the last 24 hours? Exploring the Five New Time-Series Operations Eclipse JNoSQL extends TimeSeriesTemplate with five fluent operations: latest(), earliest(), since(), until(), and last(). These methods let developers express common temporal queries directly in Java, eliminating the need for database-specific query languages. For example, consider a banking application that records six transactions for the same account at different intervals. For simplicity, we use a fixed reference time of 12:00 PM for the following observations: timeamountstatus3 days ago, 12:00 PM€10APPROVED2 days ago, 12:00 PM€11DECLINED30 hours ago€12APPROVED20 hours ago€13DECLINED10 hours ago€14APPROVED2 hours ago€15DECLINED You can insert these observations using the TimeSeriesTemplate API: Java Instant now = Instant.now(); List<Long> hours = List.of(72L, 48L, 30L, 20L, 10L, 2L); for (int i = 0; i < hours.size(); i++) { Instant timestamp = now.minus(Duration.ofHours(hours.get(i))); template.insert(new AccountTransaction( timestamp, "account-01", BigDecimal.valueOf(10 + i), "EUR", i % 2 == 0 ? APPROVED : DECLINED )); } Each observation uses an Instant as its timestamp. For the following examples, assume queries run immediately after insertion. 1. latest() — Retrieve the Most Recent Observations A customer can check their three latest transactions without manually sorting the entire history by requesting the newest observations directly. Java List<AccountTransaction> transactions = template .select(AccountTransaction.class) .latest(3); Expected results, newest first: Plain Text 2 hours ago | €15 | DECLINED 10 hours ago | €14 | APPROVED 20 hours ago | €13 | DECLINED The latest(3) operation returns up to three observations, ordered from newest to oldest. This is useful for recent transactions, monitoring dashboards, and activity feeds. 2. earliest() — Retrieve the Oldest Observations An auditing process may need to identify the first transactions recorded for an account. Java List<AccountTransaction> transactions = template .select(AccountTransaction.class) .earliest(3); Expected results, oldest first: Plain Text 72 hours ago | €10 | APPROVED 48 hours ago | €11 | DECLINED 30 hours ago | €12 | APPROVED Unlike latest(), earliest() starts with the oldest observations. This is useful for auditing, historical analysis, and identifying when a sequence of events began. 3. since() — Retrieve Observations From a Specific Time A fraud detection service may need all transactions recorded after a specific event, rather than a fixed number of observations. Java Instant start = now.minus(Duration.ofHours(36)); List<AccountTransaction> transactions = template .select(AccountTransaction.class) .since(start) .result(); Matching observations: Plain Text 30 hours ago | €12 | APPROVED 20 hours ago | €13 | DECLINED 10 hours ago | €14 | APPROVED 2 hours ago | €15 | DECLINED The since() operation includes observations at or after the specified timestamp. Unlike latest(), it does not impose a fixed result count. 4. until() — Retrieve Observations Before a Cutoff A financial reconciliation process may need to examine transactions recorded before a specific cutoff and exclude more recent activity. Java Instant end = now.minus(Duration.ofHours(12)); List<AccountTransaction> transactions = template .select(AccountTransaction.class) .until(end) .result(); Matching observations: Plain Text 72 hours ago | €10 | APPROVED 48 hours ago | €11 | DECLINED 30 hours ago | €12 | APPROVED 20 hours ago | €13 | DECLINED The until() operation includes observations at or before the specified timestamp. It is useful for historical reporting, reconciliation, and investigating earlier application states. 5. last() — Retrieve Observations Within a Relative Period A monitoring service may need to check transactions recorded during the last 24 hours. Unlike since(), which requires a specific timestamp, last() accepts a duration relative to the query execution time. Java List<AccountTransaction> transactions = template .select(AccountTransaction.class) .last(Duration.ofHours(24)) .result(); Matching observations: Plain Text 20 hours ago | €13 | DECLINED 10 hours ago | €14 | APPROVED 2 hours ago | €15 | DECLINED This operation is useful for rolling windows, such as recent errors, daily financial activity, or application metrics. Combining Temporal Operations The real flexibility comes from combining these operations. For example, imagine retrieving the two most recent transactions within the last 24 hours: Java List<AccountTransaction> transactions = template .select(AccountTransaction.class) .last(Duration.ofHours(24)) .latest(2); Expected results: Plain Text 2 hours ago | €15 | DECLINED 10 hours ago | €14 | APPROVED You can also combine conventional conditions with temporal ranges. For example, to get the latest three transactions for a specific account between 36 and 12 hours ago: Java List<AccountTransaction> transactions = template .select(AccountTransaction.class) .where("account").eq("account-01") .since(now.minus(Duration.ofHours(36))) .until(now.minus(Duration.ofHours(12))) .latest(3); Expected results: Plain Text 20 hours ago | €13 | DECLINED 30 hours ago | €12 | APPROVED Only two transactions match these conditions, even though latest(3) allows up to three results. This shows how temporal operations and traditional filtering work together without requiring database-specific queries. These five operations offer a more expressive way to work with temporal data while preserving the Eclipse JNoSQL fluent programming model. Developers can focus on business needs instead of manually constructing timestamp conditions for each database. The complete implementation, including executable examples using InfluxDB, QuestDB, and Apache IoTDB, is available in the Eclipse JNoSQL demos repository. Conclusion Time-series databases have become increasingly relevant for enterprise applications that need to analyze information over time, from financial transactions to observability and IoT. With the five new fluent API operations — latest(), earliest(), since(), until(), and last() — Eclipse JNoSQL simplifies temporal queries while preserving familiar Java persistence patterns. By supporting InfluxDB, QuestDB, and Apache IoTDB, it also provides flexibility for different architectural requirements. Explore the complete source code and discover more about enterprise Java persistence at the Eclipse JNoSQL website. More
Building Enterprise Desktop, Web, Mobile, and Docker Applications From One Shared Platform
Building Enterprise Desktop, Web, Mobile, and Docker Applications From One Shared Platform
By Dariusz Małyszko
What Actually Costs You in a Production DevOps System
What Actually Costs You in a Production DevOps System
By Manvitha Potluri
Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent
Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent
By TAPASH BISHOI
Migrating From the OpenAI API to vLLM: Configure It Right
Migrating From the OpenAI API to vLLM: Configure It Right
By Matt Sarrel

More Articles

Testing Async Code in Swift: Stop Using Task.yield() in Your Tests
Testing Async Code in Swift: Stop Using Task.yield() in Your Tests

Testing async code in Swift often turns into a lottery: tests pass locally, fail on CI, and people try to fix them with Task.yield() or Task.sleep(). Eventually the team gets used to re-running flaky builds and stops trusting the pipeline. The problem is usually a race between the test and a task that the object under test creates on its own. Task.yield() can make the test pass, but it doesn’t establish any ordering between the two. To make the test deterministic, it needs control over the tasks it creates indirectly. If you can make a method async, do it. This article is about a different situation: integrating async code into synchronous entry points you can’t control, such as UIKit and SwiftUI lifecycle methods. Why the Test Fails Take a ProfileViewModel whose load() starts a Task, fetches the user name through a service, and stores it in a property: Swift @MainActor final class ProfileViewModel { private(set) var userName = "" private let userService: IUserService init(userService: IUserService) { self.userService = userService } func load() { Task { userName = await userService.fetchUserName() } } } Swift @MainActor func testLoad() { // when viewModel.load() // then XCTAssertEqual(viewModel.userName, "Alice") // failed } The test fails because load() returns right after creating the Task, so the assertion runs before the task body does. In this case it’s not even a race: ProfileViewModel is isolated to the main actor, and a synchronous test holds the main thread until it returns. The task can only run after the assertion has already executed. Making the test async turns this into a real race between the task and the assertion, and the outcome depends on scheduling. Why Task.yield() Doesn’t Fix It A common suggestion is to yield to the created task before asserting: Swift // Dangerous, flaky test @MainActor func testLoad() async { // when viewModel.load() await Task.yield() // give way to the created task // then XCTAssertEqual(viewModel.userName, "Alice") } or, with Swift testing: Swift @Test @MainActor func load() async { // when viewModel.load() await Task.yield() // give way to the created task // then #expect(viewModel.userName == "Alice") } Locally, such a test often passes, which is what makes it dangerous. Task.yield() gives other tasks a chance to run: “if there are other tasks in the pool, you may hand control to them.” It doesn’t guarantee that the task you care about will get a thread, let alone run to completion.The task has suspension points. Inside the Task there’s await userService.fetchUserName(). A single yield may not be enough for the task to get past this await and reach the write to userName. The outcome depends on how the scheduler happens to distribute work at that moment.The result depends on load. Run such a test on a busy CI server, or repeat it 100 times in a row, and a few runs will fail at random. A flaky test is worse than a consistently red one, because a red test at least points at a real problem.Execution order is not guaranteed. Apple’s documentation doesn’t promise any specific order of execution after Task.yield(), so an assertion built on it relies on a scheduler implementation detail. Controlling Task Creation With ITaskFactory Instead of calling Task { ... } directly, we create tasks through an injected factory. The test implementation keeps track of those tasks and lets the test wait for them explicitly. Step 1: An Abstraction Over Task Creation Production code gets a task factory protocol: Swift protocol ITaskFactory { @discardableResult func task<Success: Sendable>( priority: TaskPriority?, @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success ) -> Task<Success, Never> } Protocol requirements can’t have default values, so we add a default priority through an extension: Swift extension ITaskFactory { @discardableResult func task<Success: Sendable>( @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success ) -> Task<Success, Never> { task(priority: nil, operation: operation) } } The production implementation is trivial: it just creates a task. Swift struct TaskFactory: ITaskFactory { @discardableResult func task<Success: Sendable>( priority: TaskPriority?, @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success ) -> Task<Success, Never> { Task(priority: priority, operation: operation) } } Production behavior stays the same; the factory just gives tests a way to observe the tasks being created. Step 2: A Test Factory That Remembers Every Task The test implementation keeps track of the tasks it creates and provides waitUntilIdle() to wait for them. Task has generic success and failure types, so we can’t put arbitrary tasks directly into one array. ITask gives us a common interface for waiting on them. Swift /// A protocol representing a task that can be awaited until its execution completes. protocol ITask { /// Waits for the `Task` to complete by retrieving its result. func wait() async } // MARK: - Task + ITask /// Extends the `Task` type to conform to the `ITask` protocol. extension Task: ITask { func wait() async { _ = await result } } Swift public final class TestTaskFactory: @unchecked Sendable { // MARK: Properties private let lock = NSLock() private var tasks: [ITask] = [] // MARK: Initialization public init() {} // MARK: Public /// Waits until all tasks in the queue have completed execution. public func waitUntilIdle() async { while let task = popTask() { await task.wait() } } // MARK: Private private func addTask(_ task: ITask) { lock.lock() defer { lock.unlock() } tasks.append(task) } private func popTask() -> ITask? { lock.lock() defer { lock.unlock() } return tasks.popLast() } } // MARK: ITaskFactory extension TestTaskFactory: ITaskFactory { public func task<Success: Sendable>( priority: TaskPriority?, @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success ) -> Task<Success, Never> { let task = Task(priority: priority, operation: operation) addTask(task) return task } } The while loop is important here. A task can create another task through the same factory, so waiting for the initial batch isn’t enough. We keep draining the queue until there are no tasks left. waitUntilIdle() waits for tasks to finish, so it will hang if one of them never completes (an endless for await loop, a continuation that is never resumed, a mock that never calls back). In such cases, cancel the pending tasks (for example, with a cancelAll() helper in your own test factory) or add a timeout. Also remember that it only sees tasks created through the factory. Step 3: Injecting the Factory into ProfileViewModel Swift @MainActor final class ProfileViewModel { private(set) var userName = "" private let userService: IUserService private let taskFactory: ITaskFactory init(userService: IUserService, taskFactory: ITaskFactory) { self.userService = userService self.taskFactory = taskFactory } func load() { taskFactory.task { self.userName = await self.userService.fetchUserName() } } } Step 4: A Stable Test Swift @MainActor func testLoad() async { // given let taskFactory = TestTaskFactory() let viewModel = ProfileViewModel( userService: userServiceMock, taskFactory: taskFactory ) // when viewModel.load() await taskFactory.waitUntilIdle() // then XCTAssertEqual(viewModel.userName, "Alice") } waitUntilIdle() returns only after every task created through the factory has finished, so the assertion no longer depends on scheduling. Ready-Made Implementation You don’t have to write all of this from scratch in every project. An ITaskFactory implementation, along with test doubles for tasks and DispatchQueues, is available in the open source library space-code/concurrency. It’s designed as a set of concurrency primitives that make your code more testable. The library is installed via Swift Package Manager. What About XCTestExpectation and confirmation? XCTest has XCTestExpectation and Swift testing has confirmation, so why not use them? They verify that an event happened, while here we need to know that the work has finished. A test using confirmation: Swift @Test @MainActor func load() async { await confirmation { fetched in userServiceMock.onFetchUserName = { fetched() } viewModel.load() } #expect(viewModel.userName == "Alice") } confirmation requires the confirmation to happen before the closure body returns. But load() returns immediately, and fetchUserName() is called later inside the task. The confirmation arrives too late, and the test fails. With XCTestExpectation, the test can still race: Swift @MainActor func testLoad() async { // given let called = expectation(description: "fetchUserName called") userServiceMock.onFetchUserName = { called.fulfill() } // when viewModel.load() // then await fulfillment(of: [called], timeout: 1) XCTAssertEqual(viewModel.userName, "Alice") // still a race } The expectation is fulfilled when fetchUserName() is called, which is before the task writes the result to userName. The wait is over, but the work isn’t, so the assertion races with the task again, and you also have to pick a timeout. Both tools are still the right choice for callbacks, delegates, NotificationCenter, Combine publishers, and tasks created by code you don’t control. For a Task you create yourself, waitUntilIdle() is the more direct tool. Edge Cases Task Cancellation The factory returns a Task, so you can store it and call cancel(). The test factory lets you verify this scenario too: create a task, cancel it, call waitUntilIdle(), and make sure there were no side effects. This works if the operation itself responds to cancellation correctly, for example by checking Task.isCancelled or using cancellable awaits. Don’t Overuse the Factory The factory is for places where you start a fire-and-forget task from a synchronous context, such as load() in a view model. If a method can be async itself, it’s better to make it so and simply call it with await in the test. Then you don’t need the factory at all. The approach also has a cost: every Task in production code has to go through the factory, which adds a dependency to initializers and requires discipline from the whole team. It pays off for code with real async logic that you want to cover with tests, and is overkill for trivial one-liners. Alternatives Make the API async. If load() is async, the test is just await viewModel.load(). This is the simplest option, but it moves the responsibility for creating the Task to the caller.XCTestExpectation. Suitable for external events, but it needs a timeout.Explicit task factory. It requires discipline (no direct Task { } calls), but gives full control over completion without depending on runtime details. Conclusion Task.yield() and sleep only hide the race between the test and the task. To remove it, create tasks through an ITaskFactory and wait for them in the test with waitUntilIdle(). The trade-off is an extra dependency in the initializer. For fire-and-forget tasks started from synchronous APIs, it gives the test control over task completion without relying on scheduler timing.

By Nikita Vasilev
Building a Self-Healing Docker CI Gatekeeper With BuildKit
Building a Self-Healing Docker CI Gatekeeper With BuildKit

Source code: github.com/SivaSaiKrishnaSuryadevara/docker-ci-gatekeeper. One Python file (gatekeeper.py), one deliberately broken Dockerfile, and 50 pytest tests that run on Python 3.10 through 3.13 in CI. Here is the build failure I designed this project around. It's a two-stage Python image. The builder stage compiles wheels, and the runtime stage installs them as a non-root user. Line 20 of the Dockerfile reads: Dockerfile RUN pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3 The flag is --no-cache-dir. One extra s and pip exits with code 2. BuildKit marks step [builder 4/4] as failed, the runtime stage never starts, and the pipeline goes red. The engineer who pushed it now has to open the job, scroll past base-image pulls and cache hits, find the one line that matters, fix it, push again, and wait for the whole build to queue and run from the top. None of that work requires judgment. The log already contains the answer: no such option: --no-cache-dirs. What's missing is something that reads the log the way a person would, isolates the failing instruction, proposes the smallest possible change, and proves that change works by rebuilding. That's what this gatekeeper does. It wraps docker build, turns a failed build into a structured failure record, sends that record to Claude Code in non-interactive mode (claude -p), applies the returned patch to a staging copy of the Dockerfile, and rebuilds. It gives up after two attempts. This article walks through the design decisions in the actual code, including the places where the obvious approach was wrong. The Loop, End to End gatekeeper.pyBuildFailureBuildResultAttemptGatekeeperReport--json Decision 1: BuildKit Runs Through the Docker CLI, Not docker-py My first plan was to do everything through the Docker SDK for Python. docker.from_env().images.build(...) takes a path and a Dockerfile, streams progress, and raises BuildError on failure. It looks like exactly the right tool. It isn't, because docker-py doesn't build with BuildKit. The Engine API's /build endpoint only runs BuildKit when the client also opens a session to it over gRPC. The session is how the daemon pulls files from the build context, forwards SSH agents, and serves secrets. The Docker CLI implements that session protocol. docker-py does not, so its build() call always uses the legacy builder. That matters for this project specifically, because the fixture's builder stage uses a cache mount: Dockerfile # Keep the pip cache in a BuildKit cache mount so rebuilds stay fast. RUN --mount=type=cache,target=/root/.cache/pip \ pip install --upgrade pip wheel The legacy builder rejects RUN --mount outright. If the gatekeeper used docker-py to build, it would report a "failure" that has nothing to do with the real bug, and Claude would be asked to remove a perfectly good cache mount. The fix would make the pipeline green, and the builds slower, which is worse than useless. So the default backend calls the CLI directly and forces BuildKit with plain-text progress: Python class BuildKitCliBackend: def build(self, context: Path, dockerfile: Path, tag: str) -> BuildResult: if shutil.which(self.docker_bin) is None: raise GatekeeperError(f"'{self.docker_bin}' CLI not found; install Docker or use --backend docker-py") cmd = [self.docker_bin, "build", "--progress=plain", "-f", str(dockerfile), "-t", tag, str(context)] env = {**os.environ, "DOCKER_BUILDKIT": "1"} try: proc = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=self.timeout) except subprocess.TimeoutExpired as exc: raise GatekeeperError(f"docker build timed out after {self.timeout}s") from exc output = (proc.stdout or "") + (proc.stderr or "") # BuildKit progress goes to stderr ... Two details are easy to get wrong here. --progress=plain matters because the default TTY progress renderer redraws lines in place, and a captured log of it is unreadable. And BuildKit writes its progress to stderr, not stdout, so capturing only stdout gives you an empty log on a failed build. docker-py still has a job. Before any build starts, it answers a cheaper question: is the daemon there at all? Python def preflight_daemon(timeout: int = 10) -> None: import docker from docker.errors import DockerException try: docker.from_env(timeout=timeout).ping() except DockerException as exc: raise GatekeeperError(f"Docker daemon unreachable: {exc}") from exc A missing daemon is an environment problem, not a Dockerfile problem, and it must never reach Claude. GatekeeperError maps to exit code 2, which a CI system can treat differently from exit code 1 ("the build is broken and couldn't be fixed"). This is the actual output on a machine with no Docker installed: Python $ python gatekeeper.py -f Dockerfile.broken . ERROR Docker daemon unreachable: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) $ echo $? 2 The docker-py build path does still exist as --backend docker-py, for runners that have a daemon socket but no CLI. It uses the low-level client.api.build(..., decode=True) stream and a separate parser (parse_classic_log) for the legacy builder's Step 5/9 : ... format. I'd only use it for Dockerfiles that don't use BuildKit-only syntax. Decision 2: Turn the Log Into a Typed Failure Before Anyone Reads It A raw build log is the wrong thing to send to a language model. It's long, most of it is irrelevant, and the relevant part is spread across several places. This is the real docker build --progress=plain output for the line-20 failure, captured on Docker 29.5.2 with buildx 0.37.2 under Colima (trimmed to the last cached step and the failure): Shell #8 [builder 3/4] RUN --mount=type=cache,target=/root/.cache/pip pip install --upgrade pip wheel #8 CACHED #9 [builder 4/4] RUN pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3 #9 0.146 #9 0.146 Usage: #9 0.146 pip wheel [options] <requirement specifier> ... #9 0.146 pip wheel [options] -r <requirements file> ... #9 0.146 pip wheel [options] [-e] <vcs project url> ... #9 0.146 pip wheel [options] [-e] <local project path> ... #9 0.146 pip wheel [options] <archive url/path> ... #9 0.146 #9 0.146 no such option: --no-cache-dirs #9 ERROR: process "/bin/sh -c pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3" did not complete successfully: exit code: 2 ------ > [builder 4/4] RUN pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3: 0.146 no such option: --no-cache-dirs ------ ERROR: failed to build: failed to solve: process "/bin/sh -c pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3" did not complete successfully: exit code: 2 Every BuildKit step has a numeric ID, and every line it prints is prefixed with #<id>. The step header carries the stage name and position ([builder 4/4]). The first #<id> ERROR: line identifies which step failed. parse_buildkit_log keys everything off those two patterns: Python STEP_HEADER_RE = re.compile(r"^#(?P<id>\d+) \[(?:(?P<stage>[^\s\]]+) )?(?P<pos>\d+/\d+)\] (?P<instr>.+)$") STEP_LINE_RE = re.compile(r"^#(?P<id>\d+) (?:\d+\.\d+(?: |$))?(?P<text>.*)$") Output is grouped by step ID, so the CACHED lines from step 8 and the context-transfer noise from steps 1 to 5 never end up in the failure record. Only step 9's output does. The real log taught me two things the fixture I wrote from memory had wrong. Some BuildKit versions follow the failure with a Dockerfile:<line> header and a source snippet that marks the failing line with >>>. This Docker version printed no snippet at all. And the final line now starts with ERROR: failed to build: failed to solve: rather than ERROR: failed to solve:. The parser handles both. When a snippet is present, it reads the line number from it. When it isn't, it finds the failing instruction's text in the Dockerfile with a small indexer that joins \ continuation lines and tracks which FROM ... AS <stage> each instruction belongs to. The final-line check accepts either prefix: Python FINAL_ERROR_RE = re.compile(r"^ERROR: (?:failed to build: )?failed to solve") The captured log is checked into tests/fixtures/ and parsed by test_real_docker29_log_without_snippet_block, next to the older snippet-format fixture, so both formats stay covered. For both log formats, the result is the same record. These are the values the tests assert: Python BuildFailure( category=FailureCategory.INVALID_FLAG, message="no such option: --no-cache-dirs", instruction="RUN pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3", dockerfile_line=20, stage="builder", step="4/4", exit_code=2, ... ) The Taxonomy, and Why Order Matters category comes from an ordered list of regexes. The first match wins: Python CATEGORY_PATTERNS: list[tuple[FailureCategory, re.Pattern[str]]] = [ (FailureCategory.CACHE_MOUNT, re.compile( r"--mount option requires BuildKit|invalid mount config|failed to (?:create|prepare|mount) .*cache" r"|cache mount|unknown mount (?:type|option)|mount type=cache", re.IGNORECASE)), (FailureCategory.SYNTAX, re.compile( r"unknown instruction|dockerfile parse error|failed to parse dockerfile|unexpected end of statement", re.IGNORECASE)), (FailureCategory.MISSING_FILE, re.compile( r"failed to compute cache key|failed to calculate checksum|COPY failed|ADD failed", re.IGNORECASE)), (FailureCategory.REPO_SIGNATURE, ...), # NO_PUBKEY, "is not signed", GPG error (FailureCategory.REPO_UNAVAILABLE, ...), # "does not have a Release file" (EOL Debian suites) (FailureCategory.MISSING_PACKAGE, ...), # apt "Unable to locate package", pip "No matching distribution" (FailureCategory.INVALID_FLAG, ...), # "no such option:", "unrecognized arguments" (FailureCategory.NETWORK, ...), # DNS and TLS timeouts (FailureCategory.COMMAND_FAILED, re.compile( r"did not complete successfully|returned a non-zero code|exit code: \d+", re.IGNORECASE)), ] The order encodes which explanation is most specific. Two cases show why: A misspelled cache mount type (--mount=type=cahce) makes BuildKit fail with dockerfile parse error on line 2: unknown mount type "cahce". That line matches both CACHE_MOUNT and SYNTAX. "Syntax error" is true but tells the fixer nothing. "Cache mount" points it at the right flag. So CACHE_MOUNT is checked first, and test_broken_cache_mount_parse_error pins that order.Nearly every failed RUN produces did not complete successfully: exit code: N. If COMMAND_FAILED came early, every apt and pip failure would collapse into it. It's last on purpose: it means "something in a RUN failed, and I can't say what." The message field gets the same treatment. _best_message walks the step's output and returns the first line that matches a specific category, skipping lines that match only the generic one. For an apt failure, that means the record says E: Unable to locate package libpq-devv, not exit code: 100. The parser also strips ANSI color codes and carriage returns first, because CI runners love to inject both. An unrecognized log produces UNKNOWN instead of an exception: a parser crash would take down the gatekeeper on exactly the builds it's meant to help with. Decision 3: Hand Claude a Narrow, Structured Prompt The structured record is what makes the prompt small. build_prompt sends the category, stage, failing instruction and line, exit code, key error, the last 25 lines of that step's output, and the current Dockerfile with line numbers. The rules section is short and specific: Plain Text Rules: - Change only what is needed to fix this failure. Do not restructure stages or upgrade unrelated things. - Keep every comment and parser directive (lines starting with "# syntax=", "# escape=", "# check="). - Respond with EITHER a unified diff against Dockerfile.broken (--- a/Dockerfile.broken / +++ b/Dockerfile.broken) OR the complete corrected file in a single ```dockerfile code block. No other files. - Line numbers above are for reference only; do not include them in your answer. Claude Code is invoked in print mode, from an empty temporary directory: Python with tempfile.TemporaryDirectory(prefix="gatekeeper-claude-") as scratch: proc = subprocess.run( [self.claude_bin, "-p", prompt, "--output-format", "text"], capture_output=True, text=True, timeout=self.timeout, cwd=scratch, ) The empty working directory is a deliberate containment choice. In -p mode, nobody is present to approve file edits, and I don't want Claude editing the repository directly anyway. The gatekeeper owns every write. Running from a scratch directory means the model's only output channel is stdout, which then goes through the sanitizer. A non-zero exit or a timeout raises GatekeeperError (exit 2), the same as a missing daemon. The binary path is configurable with --claude-bin or the CLAUDE_BIN environment variable. That matters on machines where Claude Code is installed somewhere other than PATH, such as inside an editor extension. On a CI runner, Claude Code must be installed and authenticated before the gatekeeper can call it. The model is configurable too, with --model or GATEKEEPER_MODEL, and I added that only after my first real run failed. My Claude Code default model was one that print mode refused without extra usage credits. claude -p exited 1 with an empty stderr, so the gatekeeper's error read claude -p exited 1: and nothing else. The explanation was on stdout: Plain Text Fable 5.1 requires usage credits. Switch to another model, or manage usage credits at claude.ai/settings/usage?from=cc_cli_limit_message, to continue. Two fixes came out of that. The error path now falls back to stdout when stderr is empty, and --model is passed straight through to claude --model: Python cmd = [self.claude_bin, "-p", prompt, "--output-format", "text"] if self.model: cmd += ["--model", self.model] ... if proc.returncode != 0: # Print mode reports some errors (auth, usage limits) on stdout, not stderr. detail = (proc.stderr or "").strip() or (proc.stdout or "").strip() raise GatekeeperError(f"claude -p exited {proc.returncode}: {detail[:500]}") Pinning the model in CI is a good idea regardless. The interactive default on a developer's machine is whatever they picked last, and a pipeline shouldn't inherit that. Decision 4: Sanitize the Patch Without Destroying the Dockerfile Model output is untrusted input. It may be a diff, a whole file, prose with a code block in the middle, or a confident explanation with no code at all. sanitize_patch turns all of those into either a complete Dockerfile or a PatchError. The order of operations: Reject anything over 200 KB (MAX_RESPONSE_BYTES).Strip ANSI codes and normalize line endings.Look for a diff first, either in a ```diff fence or bare in the response. Diff headers are checked so a patch to .github/workflows/ci.yml (or any other file) is rejected. The hunks are applied by apply_unified_diff.Otherwise, look for exactly one Dockerfile code block. Two blocks means the model is hedging, and the sanitizer refuses to pick one.Restore parser directives, then require a FROM. Why "Keep the Comments" Isn't a Formatting Nicety The obvious way to clean a model response is to strip markdown: drop headings, drop the prose. In a Dockerfile, though, every # line looks like a markdown heading. A cleaner that strips # ... lines would delete every comment in the file, and one of those "comments" isn't a comment: Dockerfile # syntax=docker/dockerfile:1.7 That's a BuildKit parser directive. It selects the Dockerfile frontend version and has to appear before any other line. Remove it and the build falls back to the daemon's built-in frontend, which can change how newer syntax like RUN --mount is parsed. A "fix" that silently drops it changes the build in a way no reviewer will see in the diff. So the sanitizer never edits inside the code it extracts. Everything outside the fence or diff is discarded. Everything inside is kept verbatim. Then, because models sometimes drop the first line of a file they reprint, the directives are put back explicitly: Python def _restore_parser_directives(original: str, patched: str) -> str: directives = [] for ln in original.splitlines(): if PARSER_DIRECTIVE_RE.match(ln): directives.append(ln) else: break # directives are only valid before the first non-directive line missing = [d for d in directives if d not in patched.splitlines()[: len(directives) + 1]] return ("\n".join(missing) + "\n" + patched) if missing else patched Stage names (AS builder, AS runtime) and ordinary comments survive because nothing in the pipeline rewrites them. If a model's full-file response does drop a comment, dropped_comments() lists it in the report and on the console as a warning, so a reviewer finds out. This is line-level handling, not an AST. The gatekeeper doesn't parse the Dockerfile into a syntax tree. It indexes instructions by line, and that's enough for the guarantees it makes: directives first, comments untouched, at least one FROM. Applying Diffs Strictly Models write unified diffs with wrong line numbers more often than they write wrong content. apply_unified_diff uses the hunk header as a hint, not an address. It tries the stated position first, then searches the whole file for the hunk's exact old lines. It applies the hunk only if there is exactly one match: Python def _find_block(lines: list[str], block: list[str], expected: int) -> int | None: if not block: return expected n = len(block) if lines[expected:expected + n] == block: return expected matches = [p for p in range(len(lines) - n + 1) if lines[p:p + n] == block] return matches[0] if len(matches) == 1 else None # ambiguous or absent: refuse Zero matches means the diff was written against a file that doesn't exist. Two or more means the hunk is ambiguous: a Dockerfile with two identical RUN apt-get update lines in two stages is a realistic example. In both cases, the gatekeeper stops instead of guessing. Decision 5: A Hard Cap of Two Attempts Each loop iteration costs a model call plus a full image build. On a multi-stage image with a cold cache, the build is usually the higher cost. A self-healing loop without a ceiling is a cost incident waiting for the right bad Dockerfile: a fix that moves the failure from step 4 to step 5, then back. The cap is enforced in code, not configuration: Python MAX_RETRIES = 2 # hard ceiling on Claude calls per run — not overridable upward def run_gatekeeper(..., max_retries: int = MAX_RETRIES, ...): if max_retries > MAX_RETRIES: log.warning("max_retries=%d exceeds hard ceiling; capping at %d", max_retries, MAX_RETRIES) retries = max(0, min(max_retries, MAX_RETRIES)) --max-retries 50 gets you 2 and a warning. --max-retries 0 is allowed: it turns the gatekeeper into a build-and-classify step with no model calls. Why two? One attempt fixes the common case: a single typo, flag, or package name. The second covers the most frequent follow-on, where fixing the first error lets the build get further and expose a second one. Past two, I'd rather a person look at it. Three failed fixes in a row usually means the build is broken in a way a one-line change won't fix. The cap is the outer limit. Two more checks inside the loop stop it earlier: unusable_patch: if the sanitizer rejects Claude's response, the loop stops immediately. It doesn't spend the second call hoping for better output.no_progress: if the "fix" is identical to the current Dockerfile, rebuilding it would just reproduce the same failure, so the loop stops. Together, these mean the worst case is fixed and small: three builds and two Claude calls per gatekeeper run. A test pins exactly that: Python def test_never_converging_fix_stops_after_two_claude_calls(self, dockerfile): backend, claude = FakeBackend(), FakeClaude() report = gk.run_gatekeeper(dockerfile, dockerfile.parent, backend, claude) assert not report.success assert report.claude_calls == 2 == len(claude.prompts) assert len(backend.calls) == 3 # initial build + one rebuild per patch assert report.stop_reason == "retries_exhausted" FakeClaude returns a new, valid, different Dockerfile on every call, so the only thing stopping that loop is the cap. Decision 6: Stage Fixes, and Write Back Only on a Passing Build Candidate fixes never touch the original Dockerfile. Each one is written to a sibling file, Dockerfile.broken.gatekeeper, and that file is what gets rebuilt: Python current = proposed working.write_text(current) build_path = working result = backend.build(context, build_path, tag) The original is overwritten only when three things are true at once: the last build passed, the content actually changed, and the operator passed --in-place: Python if result.success and current != original and in_place: dockerfile.write_text(current) working.unlink(missing_ok=True) Without --in-place, a successful run leaves the original alone and the fix in the staging file. That's the mode I'd use in CI: the job can upload the staging file and the --json report (which includes each attempt's unified diff) as artifacts, or open a pull request from them. A model-written change gets reviewed before it lands on main, and the original file is never left half-patched by a run that failed or was cancelled midway. Two tests cover both sides: test_original_dockerfile_untouched_until_build_passes and test_in_place_writes_back_on_success. One caveat I hit while writing this: BuildKit supports per-Dockerfile ignore files named <Dockerfile>.dockerignore. The staging copy has a different name, so a Dockerfile.broken.dockerignore won't apply to the rebuild. A plain .dockerignore at the context root works as usual. Testing It Without Docker or a Model The suite has 50 tests and needs neither Docker nor Claude. The build backend and Claude are replaced with small fakes that follow the same interfaces: Python class FakeBackend: """Fails while `fail_while(dockerfile_text)` is true (default: always).""" def __init__(self, fail_while=lambda text: True): self.fail_while = fail_while self.calls: list[Path] = [] def build(self, context, dockerfile, tag): self.calls.append(dockerfile) if self.fail_while(dockerfile.read_text()): return BuildResult(success=False, exit_code=1, failure=FAILURE) return BuildResult(success=True, exit_code=0) FakeBackend(fail_while=lambda text: BROKEN_RUN in text) behaves like a real build of the fixture: it fails until the bad RUN line is gone. That lets the end-to-end tests run the real parser, prompt builder, sanitizer, and staging logic against a scripted model response. The fake's first version taught me something. It originally checked whether --no-cache-dirs appeared anywhere in the file, and three tests failed with correct fixes. The fixture's header comment explains the bug, and the explanation names the bad flag, so the fake kept seeing it. The predicate now matches the full broken RUN line. A real gatekeeper doesn't have this problem because Docker doesn't execute comments, but it's a reminder that a test harness that pattern-matches over a whole file will match the comments too. The suite is split into the three guarantees the gatekeeper makes: GroupTestsWhat it provesTestBuildKitParser19Categories for invalid flags, repo signatures, EOL repos, missing apt and pip packages, network failures, cache mounts, missing COPY sources; line, stage, and step extraction; ANSI/CRLF tolerance; legacy-builder logs; a real Docker 29 logTestPatchSanitization16Fenced and bare diffs, wrong hunk offsets, full-file responses, # syntax= restoration, dropped-comment reporting, and seven classes of rejected responseTestRetryCap + TestClaudeCli15The two-call ceiling, early stops, exit codes 1 and 2, prompt contents, the claude -p invocation, --model, and stdout-only errors Plain Text $ pytest tests/ -v ... ============================== 50 passed in 0.11s ============================== GitHub Actions runs the same suite on Python 3.10, 3.11, 3.12, and 3.13 on every push. Running It Shell git clone https://github.com/SivaSaiKrishnaSuryadevara/docker-ci-gatekeeper.git cd docker-ci-gatekeeper python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt # Build, diagnose, and attempt up to two fixes. The original file is untouched; # a passing fix is left in Dockerfile.broken.gatekeeper. python gatekeeper.py -f Dockerfile.broken . --claude-bin "$(command -v claude)" --model sonnet # Same, with the full report (each attempt's failure record and diff) as JSON. python gatekeeper.py -f Dockerfile.broken . --json # Write the fix back to Dockerfile.broken only if the patched build passes. python gatekeeper.py -f Dockerfile.broken . --in-place Exit codeMeaningWhat CI should do0Build passed (as-is or after a fix)Continue; review the staging file if a fix was made1Still failing after the attempts allowedFail the job; the report shows what was tried2Environment problem: no Dockerfile, no daemon, no claude, timeoutFail the job as infrastructure, not code A Real Run With Docker running under Colima (Docker 29.5.2, buildx 0.37.2, a 4-CPU VM) and Sonnet as the model, this is the complete console output: Plain Text $ python gatekeeper.py -f Dockerfile.broken . --claude-bin "$CLAUDE" --model sonnet INFO Build failed (invalid_command_flag at line 20); asking Claude for a fix (1/2) patched Dockerfile written to Dockerfile.broken.gatekeeper attempt 0: FAIL [invalid_command_flag] line 20: no such option: --no-cache-dirs attempt 1: PASS result: PASS (passed, 1 Claude call(s)) $ echo $? 0 The whole run took about 12 seconds with the base image already pulled. Status and results go to stdout, and log lines and the staging-file notice go to stderr, so --json output stays clean for a pipeline to parse. Claude's change, from diff -u Dockerfile.broken Dockerfile.broken.gatekeeper, was one character: diff @@ -17,7 +17,7 @@ pip install --upgrade pip wheel # BROKEN: invalid pip flag (should be --no-cache-dir) -RUN pip wheel --no-cache-dirs --wheel-dir /wheels requests==2.32.3 +RUN pip wheel --no-cache-dir --wheel-dir /wheels requests==2.32.3 # ---- runtime: install prebuilt wheels only --------------------------------- FROM python:${PYTHON_VERSION}-slim AS runtime The # syntax= directive, every comment, the cache mount, and both stage names came through untouched, and dropped_comments was empty. Dockerfile.broken itself was not modified, because I didn't pass --in-place. The rebuilt image runs: Plain Text $ docker run --rm gatekeeper-build:latest 2.32.3 That's one fixture and one model, so it shows the loop works, not that it fixes every failure. But every boundary in it is real: a live daemon, a real BuildKit log, a real model response, and a real rebuild. What I'd Be Careful About One real run is one data point. The unit tests prove the parser, sanitizer, cap, and staging logic, and the run above proves the loop closes on a live daemon. Neither proves that Claude will fix your failure. That's what the rebuild step is for: treat a passing rebuild as the evidence, not the model's confidence.Log formats move. The Docker 29 log above already differed from what I expected, in two places. Capture a real failing log from your own Docker version, drop it in tests/fixtures/, and assert on it."Passes" is not "correct." A rebuild that exits 0 proves the image builds. It doesn't prove the image works. Keeping fixes in a staging file for review exists for that gap.The taxonomy is regex, and regexes drift. BuildKit and package managers reword their errors over time. An unknown message degrades to COMMAND_FAILED or UNKNOWN, which still produces a usable prompt, just a less specific one. When a category starts missing, add the new phrasing and a test with the real log line.Don't let the gatekeeper hide flakiness. A NETWORK failure isn't something a Dockerfile edit should fix. If your registry or mirror is flaky, a model may "fix" it by pinning a different mirror. The category in the report makes that easy to spot. Whether to skip the model for that category is a policy decision I've left to the pipeline. The design comes down to a few rules: the log gets parsed before the model sees it, the model never writes files, every patch is checked before it's used, nothing replaces the original without a passing build, and there are never more than two attempts.

By Siva sai krishna Suryadevara
Designing a Multi-Region Kafka Cluster for Tier-0 Workloads
Designing a Multi-Region Kafka Cluster for Tier-0 Workloads

Most of the Kafka deployments in the industry plan to survive the loss of a single Kafka broker or an availability zone. But that’s not enough for a critical Tier-0 infrastructure where downtime or data loss of even a few seconds could have a massive business impact. In such scenarios, the failure model should consider not just the loss of a broker or a zone, but the loss of an entire region. The business is expected to operate without interruption even when a whole region goes down, and it should be possible to also roll the cluster safely while operating in that state, to apply any break-glass changes. This article focuses on that kind of high-stakes deployment. Goal Design a Kafka architecture that continues to serve traffic even if one complete region goes down, with the ability to roll the cluster, one broker at a time, without availability hits. Design Decisions for Tier-0 Workloads Just running brokers in multiple regions is not the solution here. In fact, that’s the easy part. The hard question is, what guarantee remains when one of those regions disappears, and does it solve the business needs? To design for that, you need to consider several decisions together. Let’s dive into those in detail below. 1. Replica Placements Across Failure Domains This is the foundational step. For a tier-0 multi-region Kafka cluster, we need three regions with isolated failure domains and at least two brokers in each region. This ensures that one region doesn’t impact the availability of the cluster. Brokers in each region should be configured with rack awareness to indicate their failure domains as follows. Properties files # Region A broker.rack=region-a # Region B broker.rack=region-b # Region C broker.rack=region-c For tier-0 workloads, each topic's partitions should be configured to have a replication factor (RF) of 6. Kafka’s rack-aware replica assignment will spread the replicas across the three regions. If the automatic replica assignment doesn’t allocate two replicas per region, we have to explicitly reassign replicas immediately after topic creation to meet our availability guarantees. This way, if one region goes down entirely, we still have four replicas surviving, and the cluster would still continue to operate. 2. Define When Kafka Should Stop Accepting Writes The next step is to define what is considered a successful write in this Kafka setup. For this, we need two configs: Properties files # Topic level config min.insync.replicas=3 min.insync.replicas determines the minimum number of replicas that should be present in the in-sync replica set (ISR) of a partition for Kafka to accept any writes to it. This should be set at the time of topic creation to ensure high availability. Properties files # Producer side config acks=all acks=all is a producer side config that ensures that the producer will get an ack back only if the write is successful in all the in-sync replicas. These two settings work together to satisfy the durability guarantees we want. When all three regions are healthy, ISR would include all six replicas. Let’s say one region goes down; then the ISR would drop down to four. During that time, if you roll the cluster one node at a time, the ISR will go down to three. But since minISR is three, writes will still continue to work. Kafka will stop accepting writes only when one whole region and two brokers in a different region go down at the same time. Cluster stateISRMin isr=3writes All 3 regions healthy 6 Satisfied Continue Region-A down 4 Satisfied Continue Region-A + one broker down 3 Satisfied Continue Region-A + two brokers down 2 Not satisfied Rejected The goal isn’t availability at any cost; rather, the system should be available as long as the durability guarantees that we designed for can be maintained. 3. Architecting the KRaft Quorum for Tier-0 So far, we focused on the data plane. Now switching gears, the KRaft controllers have a completely different availability model. They form the metadata quorum, and a majority is needed to continue operation. In our setup, we can distribute five controllers as 2 + 2 + 1 across the three regions, requiring a majority of three to maintain quorum. If either of the regions containing two controllers goes down, three controllers remain. If the region containing one controller goes down, four remain. So, the controller quorum survives the loss of any one region. But, unlike brokers, we cannot roll the controllers at that point because taking one controller down would cause the quorum to drop below three. To solve this, we need more controllers, and a 3 + 3 + 3 distribution would provide this. Losing one region would leave six controllers with room to still roll the controllers, as we only need five to maintain quorum. On the flip side, an increase in quorum size also increases the coordination overhead. The official Kafka documentation typically recommends three or five controllers, which tolerate one or two concurrent failures, respectively. Our 3 + 3 + 3 setup is driven by the stricter failure requirement we defined above. You need to consider if you want the same availability guarantee for the controllers as that of the data plane and decide on the controller quorum setup. 4. Hidden Cost of WAN The availability guarantees we discussed come with their own cost. The first cost is client latency. With cross-region replication and acks=all, the network latency between these regions directly affects the producer latency. Consumers can also pay the WAN latency cost when they are consuming from partition leaders located in a different region. The second cost is replication overhead. With RF=6, there is additional storage, network traffic, and replication-related coordination cost in the brokers compared to a smaller number of replicas. The third cost is the landmine. The WAN itself becomes a failure mode. In this setup, a partly working WAN between two regions can be more dangerous than a link that’s completely down. Increased latency, packet loss, or intermittent connectivity issues between regions can cause replication to lag, ultimately resulting in replicas falling out of ISR. The three regions might be independently healthy, but if the connectivity between them is not, then the availability of the cluster might be impacted. Going back to the CAP theorem, to tolerate a network partition, we must choose between consistency and availability. So, if a partition's ISR falls below the configured min.insync.replicas of three due to network partition, Kafka stops accepting writes rather than weakening those guarantees. Similarly, if the KRaft controller quorum is lost, then no metadata changes (like leader elections, etc.) can happen in the cluster, even though existing data-plane traffic may continue for some time. So, in an architecture like this, monitoring the health of the network paths between these regions is as critical as monitoring the Kafka brokers and controllers. Metrics like round-trip latency (RTT) between regions, packet loss, TCP retransmissions, connection errors/timeouts, and network throughput/bandwidth utilization are a good start. 5. Capacity Plan for the Failure State When one region goes down, all the partition leaders in that region would move to the two other surviving regions. This implies that those two regions would have to handle more producer and consumer traffic, network throughput, and disk I/O. Even if the cluster is designed to satisfy its ISR and controller quorum requirements, if it's not sized to handle these failures when one region goes down, the surviving regions would be overloaded, resulting in higher latencies, timeouts, and operational instability. So, for Tier-0 infrastructure, capacity planning should always be done for failure states and not stop at normal operations. Region recovery should be planned as well. When a failed region comes back up, those brokers might have to catch up on a significant amount of data before they start accepting traffic, resulting in a sudden burst of cross-region network traffic and disk I/O across all regions. Therefore, recovery needs to be controlled in order to not overwhelm the healthy part of the cluster. This can be achieved by throttling the replica catch-up with the trade-off of longer recovery time to minimize impact on live production traffic. Replication throttling needs a deeper discussion of its own, so we won’t go into details here. Tier-0 Multi-Region Kafka Checklist To summarize, before putting a Tier-0 multi-region Kafka cluster into production, validate these five things: Replica placement: Are brokers spread across three regions with at least two brokers per region configured with the right broker.rack settings?Write durability: Are all Tier-0 topics configured with replication.factor=6, min.insync.replicas=3 and producers use acks=all?KRaft quorum: Can the controllers lose any region and still maintain quorum, with enough headroom to lose or restart another controller if required?Cross-region cost: Is the cross-region latency with acks=all acceptable, and are WAN latency, packet loss, replication lag, and ISR changes actively monitored?Failure-state capacity: Can the two surviving regions handle the production workload, with enough network and disk headroom for the replicas to safely catch up when the failed region recovers? Conclusion There is no shortage of ways to deploy Kafka across multiple regions. The challenge is picking the right architecture that meets all our durability guarantees. For Tier-0 workloads, this means designing the architecture around failures first. What happens when a region goes down? Can we still roll the cluster? What continues to work, and at what point do we deliberately stop accepting writes? Lastly, can we safely bring back the region that was down without impacting the business? That is ultimately the difference between simply running Kafka in multiple regions versus actually supporting a mission-critical Tier-0 workload.

By Harini Rajendran
Why More Executors Don't Always Make Spark Faster: Understanding AQE
Why More Executors Don't Always Make Spark Faster: Understanding AQE

When a Spark job runs long, one of the easiest fixes to reach for is more compute. The instinct is understandable: if the cluster is busy, give it more workers and more memory. The problem is that a slow Spark job is not always a capacity problem. Sometimes the cluster has plenty of resources, but the work is divided badly, or the original query plan no longer matches the data that actually shows up at runtime. A familiar example is a stage with 200 tasks where 199 finish in roughly 20 seconds and one task runs for several minutes. The job is not waiting because the cluster needs 20 more executors. It is waiting because one task received far more work than the rest. The opposite can happen too: Spark may create hundreds of tiny tasks, each processing only a few megabytes, so scheduling overhead becomes noticeable. Joins introduce another variation: Spark can choose a reasonable strategy before execution, then discover after filtering that one side of the join is much smaller than expected. Adaptive Query Execution (AQE) is useful in all three situations because it lets Spark reconsider parts of the physical plan using information collected while the query is running. The feature matters less as a checkbox and more as a change in how we troubleshoot Spark: instead of asking only how much compute a job needs, we first ask what is actually making the job slow. What AQE Actually Does Spark creates a physical plan before it executes a SQL query or DataFrame operation. That plan includes choices such as the join method, the number of shuffle partitions, and how data should move between executors. Those choices are based on statistics and estimates available at planning time. They are often good enough, but they are still estimates. Once execution begins, Spark learns things that were impossible to know precisely beforehand. A filter may reduce a large table to a small intermediate result. A shuffle may produce many tiny partitions. One key may create a partition several times larger than the others. AQE uses those runtime statistics to adjust work that has not yet executed. A useful analogy is a GPS route. You start with the best route available, but if traffic conditions change or new information arrives, the GPS adjusts the remaining path. It cannot undo the road already traveled; it can only improve what comes next. AQE works the same way around materialized query stages. Figure 1. Spark starts with an estimated plan, collects runtime statistics, and can revise later stages when the real data differs from the estimate. Problem 1: One Task Is Much Slower Than the Rest One of the clearest Spark performance symptoms is a stage that looks almost finished but refuses to complete. Most tasks are green, CPU usage may already be falling, yet one task keeps running. This is usually a better clue than the total job duration. At this point, adding executors is not the first thing to try. The useful question is why the last task has so much more work. A common cause is data skew. What Data Skew Looks Like Spark processes data in partitions. Parallel execution works best when those partitions contain roughly similar amounts of work. A balanced shuffle might produce partitions around 180-210 MB each. A skewed shuffle can look very different: The fourth partition is the outlier. While several executors finish their 200 MB tasks, one executor still has gigabytes left to process. That is why a Spark UI can show free CPU even though the stage has not completed. The bottleneck is not lack of workers; it is the shape of the work. Skew often comes from a small number of very frequent keys: a default identifier, an unknown category, a null-like value, or simply a naturally popular key. Nothing has to be 'wrong' with the data for skew to exist. How AQE Helps With Skew After a shuffle materializes, Spark knows the actual size of the resulting partitions. For supported joins, AQE can identify an oversized partition and split that work into smaller pieces before later tasks run. Figure 2. Before AQE, one oversized partition creates a straggler. Adaptive skew handling can split the work into smaller pieces so more tasks can progress in parallel. What to Check in the Spark UI When a stage seems stuck near completion, compare tasks rather than relying on the average. Look at the longest task, its shuffle read size, and whether it spilled much more data than the others. Spill occurs when Spark cannot keep all of an operation's intermediate data in memory and has to use disk. This is a more useful diagnosis than simply saying that the job took 30 minutes. It tells you where to look next. A Practical Skew Investigation Consider a stage with 240 tasks. The first 239 finish in about 25 seconds, while the final task runs for more than six minutes. At first glance, the cluster can look underpowered because the stage is still active. But the task metrics tell a different story: most tasks read between 150 and 220 MB of shuffle data, while the straggler reads 5.6 GB and spills heavily to disk. In that situation, increasing the executor count is unlikely to be the first useful move. The other executors have already finished their work. The better next step is to inspect the key distribution and the final adaptive plan. If AQE marks the join as skewed and splits that oversized partition, the bottleneck was work distribution rather than raw cluster capacity. Problem 2: Spark Creates Too Many Small Tasks The opposite failure mode is less dramatic but surprisingly common: instead of one task doing too much, Spark schedules hundreds or thousands of tasks that do almost nothing. The query is still correct, but the amount of coordination starts to compete with the useful work. Every task has overhead. Spark has to schedule it, an executor has to start it, shuffle blocks may need to be fetched, and the driver has to track progress. When each task processes only a tiny amount of data, those fixed costs become noticeable. Why More Partitions Are Not Always Better It is tempting to treat partition count as a simple parallelism dial: more partitions should mean more workers can run at once. That is true only up to a point. Too few partitions create large tasks that may spill or run for a long time. Too many partitions create tiny tasks and unnecessary scheduling overhead. A single fixed value is also hard to justify when the same workload changes from day to day. A query might process 30 GB on Monday, 15 GB on Wednesday, and 180 GB at month end. A partition count that feels sensible for 180 GB can be wasteful for 15 GB. How AQE Coalesces Small Shuffle Partitions Once the shuffle has finished, Spark knows how much data each output partition actually contains. AQE can combine adjacent small partitions before the next stage begins. The exact grouping depends on the workload and configuration, but the idea is simple: Spark is no longer forced to carry the original shuffle partition count into the next stage when the data proves that many of those partitions are unnecessarily small. A Practical Over-Partitioning Example Imagine a daily aggregation configured with 2,000 shuffle partitions because month-end runs can be very large. On an ordinary weekday, filters reduce the input so aggressively that the next stage receives only a few gigabytes. The Spark UI then shows hundreds of tasks completing in well under a second. Nothing is technically broken, but the stage spends a noticeable amount of time creating, scheduling, and tracking work that contains very little data. That is a good case for checking whether AQE coalesced the post-shuffle partitions. If the final adaptive plan shows fewer, larger shuffle reads, Spark is matching the task count to the data that actually arrived rather than blindly preserving the original partition count. Problem 3: The Original Join Strategy Becomes Expensive Joins are where planning-time estimates become especially visible. Suppose Dataset A is large and Dataset B is estimated at 150 MB. Spark may reasonably choose a sort-merge join, which can involve shuffling and sorting both sides. Now assume Dataset B has a selective filter. After that stage runs, the intermediate result is only 7 MB. The physical problem is no longer the one Spark planned for. Broadcast Join in Simple Terms When one side of a join is small enough, Spark can send a copy of that small relation to the workers processing the large dataset. Each worker can then perform the join locally instead of redistributing both sides across the cluster. Broadcast is not automatically better for every join, but it can avoid significant shuffle and sort work when one side is genuinely small. Where AQE Helps The planner may have seen 150 MB before execution. After filtering, AQE can see that the actual intermediate result is 7 MB. If the runtime conditions support it, the remaining plan can switch from a sort-merge join to a broadcast hash join. The SQL did not change. The underlying table did not change in the middle of the job. What changed was Spark's knowledge about the data reaching the join. A Practical Join Example Suppose a reference table is usually large enough that a sort-merge join is a sensible choice. A particular report, however, filters that table to a narrow date range and a small set of categories. The planning estimate still makes the relation look substantial, but after the filter runs the materialized result is only a few megabytes. If the final adaptive plan changes the join to a broadcast hash join, that is evidence that runtime information changed the economics of the query. This is more useful than simply saying that AQE 'made the job faster': it explains which assumption changed and why a different strategy became reasonable. Good Statistics Still Matter AQE does not make table statistics irrelevant. A good initial plan is still better than correcting an avoidable mistake later. The challenge is that stored table statistics describe source data more easily than they predict every intermediate result after several filters and transformations. The source table is large; the relation entering the next operator is not. AQE helps because that second number becomes known only after part of the query has actually run. How the Three Problems Look Different The most useful Spark tuning skill is not memorizing every AQE setting. It is learning to recognize the pattern in front of you. What you notice What to investigate One task runs much longer than the others Data skew or an oversized partition One task reads far more shuffle data Data skew Hundreds of tasks finish almost immediately Too many small post-shuffle partitions A join produces a large shuffle Join strategy and input sizes One join side becomes tiny after filtering Whether broadcast becomes practical Most time is spent reading source files Storage layout, pruning, or scan cost before AQE Most tasks spill heavily Tasks may be too large or memory pressure may exist Initial Plan vs. Final Plan With AQE, a pre-execution physical plan is only the first version of the story. The initial plan tells you what Spark expected to do. The final adaptive plan tells you what it decided after seeing runtime statistics. That difference is useful evidence. It shows that the runtime data materially changed the execution strategy. The same idea applies when AQE coalesces shuffle partitions or handles a skewed join. Why EXPLAIN Does Not Tell the Whole Story `EXPLAIN` is valuable because it shows the plan Spark currently expects to use. The limitation is that AQE depends on runtime information. A pre-execution explain plan cannot contain statistics from stages that have not run yet. For AQE troubleshooting, use both views: the plan before execution and the executed/final adaptive plan together with Spark UI metrics. One shows the assumption; the other shows what actually happened. A Simple Troubleshooting Process If a Spark workload takes 30 minutes, resist the urge to start by changing configuration. A short diagnostic pass usually gives you a much better target. Find the slowest stage: Identify where most of the job time is concentrated. If one stage accounts for 20 of the 30 minutes, start there.Look at the tasks inside that stage: Compare median and maximum task time. One extreme task suggests a very different problem from thousands of tiny tasks.Inspect shuffle data: Large shuffle read/write values point toward joins, aggregations, partition sizing, or skew.Look at the join strategy: If the expensive stage contains a join, compare the chosen strategy with the actual input sizes that materialized.Compare the initial and final plans: Check whether AQE coalesced partitions, handled skew, or changed a join strategy.Tune only after identifying the bottleneck: Now a configuration change has a specific reason behind it instead of being a guess. What Not to Do Automatically Several common Spark tuning actions are perfectly reasonable when they match the problem. They become expensive trial-and-error when they are used as defaults. Adding executors helps when the workload has enough independent work to use them. It may do little when one skewed task is the bottleneck.Increasing shuffle partitions can help when tasks are too large, but it can make scheduling overhead worse when the stage already contains many tiny tasks.Forcing a broadcast join can be effective when one relation is reliably small, but it can be risky when that relation varies significantly between runs.Using one partition count for every workload is operationally simple, but it ignores differences in data volume and distribution. The configuration value is rarely the diagnosis. The useful part is knowing which behavior you are trying to change. What AQE Cannot Fix AQE is helpful, but it is not a substitute for good data engineering. If a query reads 2 TB when it only needs 50 GB, AQE does not remove the unnecessary scan. If a table contains thousands of badly sized files, AQE does not redesign the storage layout. It will not rewrite inefficient business logic or make two genuinely huge join inputs magically small enough to broadcast. Good filtering, file layout, table design, statistics, and query structure still matter. AQE adds resilience when runtime conditions differ from planning-time assumptions; it does not make those fundamentals optional. A Better Way to Think About Spark Performance A common troubleshooting pattern is 'slow job -> add more compute.' A more reliable sequence is to narrow the problem before deciding what to change. This approach takes a few extra minutes before the first configuration change, but it usually saves much more time than repeatedly resizing the cluster and rerunning the job. Conclusion A slow Spark job does not automatically mean the cluster is too small. One task may have received far more data than the others. A shuffle may have produced hundreds of tiny tasks. A join strategy may have been chosen using an estimate that no longer matches the filtered data. AQE helps because Spark can react to some of these conditions after execution begins. It can coalesce small shuffle partitions, split certain skewed join partitions, and change some join strategies when runtime relation sizes make a better option possible. The larger lesson is about diagnosis, not a single Spark feature. Start with the slow stage. Look at the task distribution. Check shuffle and spill. Inspect the join. Then compare the initial plan with the final adaptive plan. Once you know what Spark learned at runtime, the tuning decision is usually much easier to justify. In practice, this also prevents a common tuning trap: changing several settings at once and then not knowing which change mattered. A small amount of observation up front usually makes the eventual fix easier to explain, repeat, and defend.

By Harsh Patel
Getting Started With Weaviate: Building AI-Powered Search Applications With Java
Getting Started With Weaviate: Building AI-Powered Search Applications With Java

Developing AI-powered enterprise applications involves challenges beyond vector storage and retrieval. Developers need to integrate embedding models, support semantic and keyword searches, and manage infrastructure that connects databases to AI services. As requirements expand, maintaining separate components becomes more complex. Weaviate, an open-source vector database built for AI integration, addresses these issues by unifying vector search, hybrid retrieval, and optional machine learning integrations in a single platform. Weaviate enables Java developers and software architects to simplify intelligent search architectures while maintaining control over data persistence and AI integration. Its modular design supports various embedding providers, retrieval strategies, and deployment environments. This article examines Weaviate's capabilities, demonstrates local configuration with Docker, and shows integration with enterprise Java using Eclipse JNoSQL. Before implementation, we will review what sets Weaviate apart and its practical benefits. Understanding Weaviate: Architecture and Real-World Applications Weaviate is an open-source vector database written in Go that manages structured objects and their vector representations. Its modular AI integration architecture distinguishes it from other solutions. Developers can connect embedding models, rerankers, and generative AI services directly to the database, minimizing the need for independent orchestration at the application layer. For example, in an enterprise knowledge management platform with technical documentation, internal procedures, and support articles, a developer searching for “how to improve Java application performance” benefits from semantic retrieval. In contrast, a search with an exact error code requires precise keyword matching. Weaviate addresses both needs through hybrid search, combining vector similarity with BM25 keyword retrieval and configurable ranking strategies. Weaviate offers several features relevant to enterprise architectures: Integrated AI models: Optional modules connect to embedding providers, rerankers, and generative AI models. Applications may also generate embeddings externally and provide their own vectors.Hybrid search: Combines semantic similarity and keyword matching, allowing developers to balance conceptual relevance with exact terminology.Named vectors: Associates multiple vector representations with an object, enabling different embedding strategies for the same information.Multi-tenancy: Supports tenant-specific data isolation within collections, making it useful for SaaS applications serving multiple organizations.Flexible indexing: Offers HNSW, flat, and dynamic vector indexes, giving architects options for balancing resource consumption and retrieval performance. While these capabilities are not unique to Weaviate, its modular architecture effectively integrates data persistence, search, and optional AI operations. This convenience also raises architectural decisions about where to place embedding generation, model dependencies, and application responsibilities. Weaviate in Real-World Applications Weaviate’s published customer stories illustrate how organizations apply vector search to different enterprise requirements: Booking.com: Selected Weaviate for its centralized embedding service, supporting search and machine learning workloads across internal teams. Its published case study reports improved performance and about 40% lower costs than its previous solution.Kapa.ai: Uses Weaviate as a core component of its AI-powered technical support platform, helping organizations retrieve relevant answers from documentation and knowledge bases. These examples highlight two architectural requirements: managing large-scale vector infrastructure and building specialized AI-powered applications. They show that vector databases can function as shared enterprise infrastructure or as components of individual products. However, adding more AI capabilities to the database does not guarantee a better architecture. External embedding generation can provide greater application-level control, while database-managed integrations may simplify development but require additional configuration and provider dependencies. The best approach depends on operational requirements, portability, and how responsibilities are distributed across the system. For our Java example, we will handle embedding generation within the application using LangChain4j and use Weaviate for vector persistence and retrieval. This separation lets us explore Weaviate’s capabilities through Eclipse JNoSQL without adding extra AI services to the database configuration. Next, run Weaviate locally with Docker and connect it to a lightweight Java SE application. Setting Up Weaviate With Docker Weaviate supports multiple deployment options, such as managed cloud services, Docker containers, and Kubernetes clusters. In this article, we will use Docker to run Weaviate locally, enabling us to explore its vector search capabilities without relying on cloud infrastructure or external AI services. To start Weaviate, use the following command from our example repository: Shell docker run -d --name weaviate-instance \ -p 8080:8080 -p 50051:50051 \ -e AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED=true \ -e PERSISTENCE_DATA_PATH=/var/lib/weaviate \ -e DEFAULT_VECTORIZER_MODULE=none \ semitechnologies/weaviate:1.38.21 This configuration exposes port 8080 for HTTP and 50051 for gRPC. Automatic vectorization is disabled with DEFAULT_VECTORIZER_MODULE=none because our Java application will generate embeddings using LangChain4j. Anonymous access is enabled for local testing but should not be used in production without proper security controls. Once Weaviate is running, connect it to Eclipse JNoSQL, which offers a unified persistence abstraction for NoSQL databases. Integration with Jakarta EE and CDI allows developers to use a consistent programming model across REST applications, background services, and batch workloads. For simplicity, our example uses Java SE with CDI and does not require an application server. The Maven configuration includes the Weaviate driver and LangChain4j to enable local embedding generation: XML <dependency> <groupId>org.eclipse.jnosql.databases</groupId> <artifactId>jnosql-weaviate</artifactId> <version>${jnosql.version}</version> </dependency> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-embeddings-all-minilm-l6-v2-q</artifactId> <version>${langchain4j.embeddings.version}</version> </dependency> The complete project includes additional dependencies. Next, configure Weaviate using MicroProfile Config in META-INF/microprofile-config.properties: Properties files jnosql.vector.database=products jnosql.weaviate.host=localhost jnosql.weaviate.http.port=8080 jnosql.weaviate.grpc.port=50051 The products collection stores the catalog, and the other properties specify the Weaviate endpoints. Unlike previous Milvus and Qdrant examples, this repository does not require specifying a vector dimension or distance metric in the MicroProfile configuration. With the database configured, we can now demonstrate how Java applications persist objects, generate embeddings, and perform similarity searches using Eclipse JNoSQL. Exploring Weaviate With Enterprise Java Once Weaviate is running, we can focus on the application. Eclipse JNoSQL offers VectorTemplate, a Jakarta NoSQL Template specialization that combines standard persistence with vector similarity search. Developers can use familiar Java objects without managing Weaviate’s native API directly. Returning to our product recommendation example, we can map a product using Jakarta NoSQL annotations: Java @Entity public class Product { @Id private String id; @Column private String name; @Column private String description; @Column private ProductType type; @Column private Vector embedding; // Constructors and getters } The embedding attribute stores the vector representation, while the other attributes provide structured product information. Since Weaviate’s automatic vectorization is disabled, our Java app To generate embeddings, we use LangChain4j with a local embedding model and convert its output into Eclipse JNoSQL’s DenseVector: Java @ApplicationScoped public class TextEmbedder { private final EmbeddingModel model = new AllMiniLmL6V2QuantizedEmbeddingModel(); public Vector embed(String text) { float[] values = model.embed(text) .content() .vector(); return DenseVector.of(values); } } This approach avoids external AI API dependencies while keeping embedding generation independent of the persistence layer. We can then create and insert products using VectorTemplate: Java String text = """ Product: %s Description: %s """.formatted(name, description); Vector embedding = embedder.embed(text); Product product = new Product( id, name, description, type, embedding); template.insert(product); The inserted product includes both business attributes and its numerical representation, which is especially useful for semantic searches. Semantic Search and Structured Filtering For example, if a customer searches for “listen to music without cables,” the application generates a query embedding and retrieves similar products without requiring an exact keyword match: Java Vector queryVector = embedder.embed( "listen to music without cables" ); List<Product> products = template.search(Product.class) .vector(queryVector) .limit(Limit.of(3)) .result(); This query can identify relevant products, such as wireless headphones or Bluetooth speakers, even if product descriptions use different terminology. Enterprise applications often combine semantic retrieval with business constraints. For example, we can restrict the search to electronics: Java List<Product> products = template.search(Product.class) .vector(queryVector) .where("type").eq(ProductType.ELECTRONICS) .limit(Limit.of(3)) .result(); Eclipse JNoSQL combines vector similarity with structured conditions, enabling Weaviate to retrieve relevant products within a selected category. This is filtered vector search. Weaviate’s native hybrid features, such as BM25 keyword ranking, are separate capabilities. Beyond VectorTemplate: Jakarta Data and Jakarta Query Eclipse JNoSQL supports Java persistence through three complementary specifications: Jakarta NoSQL, Jakarta Data, and Jakarta Query. Jakarta NoSQL provides entity mapping and template operations. Jakarta Data introduces repository abstractions, and Jakarta Query defines a common query language foundation. For example, Jakarta Data allows developers to express standard persistence operations through a repository: Java @Repository public interface ProductRepository extends BasicRepository<Product, String> { } With a compatible repository provider, this abstraction offers operations such as save(), findById(), and deleteById() without requiring implementation of the underlying persistence logic. Specialized vector searches are still available through VectorTemplate. The repository is an illustrative example and is not included in the supplied Weaviate demo. Jakarta Query integration is a separate, evolving capability. This combination lets developers choose between standard persistence operations and specialized vector retrieval while maintaining a familiar Java programming model. While Weaviate offers additional AI integrations, our example shows that applications can manage embeddings independently and use the database mainly for persistence and retrieval. The complete implementation, including the Java SE bootstrap and executable examples, is available in the Eclipse JNoSQL Weaviate demo. Conclusion Weaviate offers a flexible solution for building AI-powered search applications by combining vector persistence, hybrid retrieval, and optional AI model integrations. Its modular architecture allows Java developers and software architects to balance application responsibilities, search features, and operational complexity. With Eclipse JNoSQL, we demonstrated integrating Weaviate into enterprise Java using familiar persistence APIs, while maintaining independent embedding generation with LangChain4j. To review the implementation and learn more about polyglot persistence, please visit the Eclipse JNoSQL website for the complete source code.

By Otavio Santana DZone Core CORE
Designing a Data Pipeline for Multi-Location Marketing Attribution (Before You Actually Need One)
Designing a Data Pipeline for Multi-Location Marketing Attribution (Before You Actually Need One)

Marketing teams rarely think of their tool stack as a data pipeline problem, but that's exactly what it is once more than one location and more than one channel are involved. The symptoms show up as bad reporting — inconsistent lead counts, cost-per-lead numbers that don't reconcile between platforms, attribution that seems to shift depending on which dashboard you're looking at. The root cause is architectural: there's no ETL process turning raw platform data into a single, trustworthy dataset. Here's what building that pipeline properly actually involves. The Problem With "Just Check the Dashboards" A typical multi-location marketing stack has, conservatively, five separate systems generating conversion data: Google Ads, Meta Ads, a CRM, a review/reputation platform, and a Google Business Profile per location. Each has its own API, its own conversion definition, its own attribution window, and — critically — no awareness that the other four systems exist. Checking each dashboard individually works fine for one location. It breaks down almost immediately at scale because nothing reconciles numbers across systems. A lead near the boundary between two nearby locations can get attributed differently depending on which platform's default logic happens to process it first — and there's no layer catching or correcting that inconsistency, because no layer currently owns that responsibility. Extract: Pull Raw Events, Don't Trust Native Aggregates The first design decision matters more than it sounds like it should: pull raw event-level data from each platform's API (individual conversions, individual leads, individual reviews) rather than relying on each platform's own pre-aggregated dashboard numbers. This matters because native dashboards apply each platform's own attribution logic before you ever see the number. By the time a dashboard shows you "42 conversions," Google Ads has already made attribution decisions you can't see or override. Pulling raw events means those decisions get made once, consistently, in your own transform layer — not five times, inconsistently, by five different platforms. Here's the core of the problem in miniature — two raw events, same customer action, two completely different shapes coming out of two different platform APIs: JSON // Raw event from Google Ads API { "conversion_action": "lead_form_submission", "campaign_id": "20481093", "gclid": "Cj0KCQiA...", "conversion_value": 1, "conversion_date_time": "2026-09-01 14:22:03" } JSON // Raw event from Meta Ads API (same real-world lead, different shape) { "event_name": "Lead", "ad_id": "1204988531", "form_id": "994211003", "value": 1, "event_time": 1756736523 } Neither payload contains a location_id. Neither uses the same field names, timestamp format, or a definition of "value." Feed both of these into two separate dashboards, and you get two internally consistent but mutually incompatible pictures of the same underlying event. Transform: One Canonical Schema, Location as a Required Field This is the step that's usually skipped, and it's the one that matters most. Every event — regardless of source platform — gets mapped to one canonical schema: JSON { "event_id": "uuid", "event_type": "lead | conversion | review | inquiry", "location_id": "required, not inferred", "channel": "google_ads | meta_ads | organic | referral", "qualified": true, "timestamp": "2026-09-01T14:22:03Z", "raw_source_id": "original platform's ID, for traceability" } The two previous raw payloads map into this one shape — the Google Ads event and the Meta event become directly comparable, directly attributable to a location, and directly aggregable — because they now share a schema instead of just sharing a business. Two details matter here more than the rest of the schema. First, location_id is required at ingestion — tagged from the campaign or account configuration, never reconstructed downstream from naming conventions or geographic guesswork. Second, qualified is computed against one shared, documented definition applied uniformly across every source, not left to whatever each platform happens to call a "lead" by default. Skip this step, and you don't have a pipeline; you have five feeds pointed at the same dashboard — which is the situation most multi-location businesses are actually in without realizing it's a design gap rather than a reporting nuisance. Load: One Warehouse, One Source of Truth Once events are normalized, they land in a single warehouse — it doesn't need to be exotic; a straightforward relational store is enough at most franchise scales. The point isn't the technology. The point is that this warehouse, and nothing else, becomes the source of truth for reporting. Individual platform dashboards remain useful for platform-specific optimization (bid adjustments, creative testing), but stop being trusted for cross-channel or cross-location comparison, because they were never built to make that comparison correctly in the first place. Once the data lives in one place with a consistent schema, the query that used to require manually reconciling five dashboards becomes trivial: SQL SELECT location_id, channel, COUNT(*) AS total_leads, SUM(CASE WHEN qualified THEN 1 ELSE 0 END) AS qualified_leads FROM marketing_events WHERE event_type = 'lead' AND timestamp >= '2026-08-01' GROUP BY location_id, channel ORDER BY location_id, qualified_leads DESC; That single query — impossible to run accurately against five disconnected native dashboards — is the entire point of building the pipeline in the first place. Why Building This Early Beats Building It Late The honest case for building this pipeline isn't urgency — it's cost curve. At two locations, inconsistent attribution is a minor, absorbable annoyance. At twenty, it's the difference between confidently reallocating budget toward what's actually working and reallocating budget based on an artifact of which platform's attribution model happened to win a particular reporting period. Retrofitting this after scaling means reconciling months or years of inconsistent historical data against a schema that didn't exist when the data was generated — a genuinely painful migration. Building it while the location count is still small means the schema and pipeline mature alongside the business, instead of getting bolted on after the fact, under pressure. Where This Fits in the Broader Marketing Stack None of this replaces marketing strategy: targeting, creative, budget allocation still require real expertise. What it does is make sure the inputs to those decisions are trustworthy, which is a precondition most multi-location marketing setups quietly skip. A brilliant targeting strategy built on inconsistently attributed data is still working from bad inputs; the pipeline is what makes every downstream decision — in paid advertising, in social strategy, in location-level reporting — actually reliable.

By James Watson
Fast Service but Slow Client: When a Sidecar Makes Sense
Fast Service but Slow Client: When a Sidecar Makes Sense

At a previous organization, we had an internal service that was called from several fairly important request paths. It wasn't doing anything glamorous. Given some request context, it returned tenant-related metadata that other services needed before they could continue processing. The service was designed to be fast. Its latency was usually in the single-digit millisecond range, including at the higher percentiles, and it had very high availability. It was also called frequently enough that we paid attention to even relatively small changes in latency. Then one of the consuming teams started complaining that it wasn't performant. Their measurements were hard to reconcile with ours. The service team's dashboards looked healthy, but from the application team's point of view, the dependency was clearly adding much more latency than it should. There were also failures they associated with the service. This is one of those situations where looking at another dashboard doesn't help much. We had to follow how that particular application was actually using the service. Once we did that, the discrepancy made more sense. Some operations that could have been performed concurrently were happening sequentially. The client also wasn't following all the retry and failure-handling practices that had evolved around the service. So the service could report a perfectly healthy P99 while the application still experienced poor end-to-end behavior. Both measurements were correct. That incident eventually pushed us toward a sidecar, but the interesting part wasn't really the sidecar itself. The more important question was why every consuming team was responsible for independently knowing the best way to communicate with this service. Service Latency Is Not Client-Perceived Latency People sometimes talk about service latency as if it were a single number. It isn't. Imagine a service operation takes 4 or 5 milliseconds. That looks great on the server dashboard. Now imagine the application needs several independent pieces of information and happens to retrieve them one after another: Java lookup A -> wait lookup B -> wait lookup C -> wait continue A simplified implementation might look like this: Java Tenant a = client.lookupA(id); Tenant b = client.lookupB(id); Tenant c = client.lookupC(id); Nothing about that code looks outrageous. In fact, this is the kind of implementation that can survive code review because each individual call is reasonable. But if the calls are independent, the application is unnecessarily adding their latencies together. It might instead do something conceptually closer to: Java Future<Tenant> a = asyncLookupA(id); Future<Tenant> b = asyncLookupB(id); Future<Tenant> c = asyncLookupC(id); waitForAll(a, b, c); Now the elapsed time is closer to the slowest operation instead of the sum of all three. Our real implementation was obviously more complicated than those few lines, but this was one of the issues we found: the calling pattern mattered almost as much as the performance of the service itself. Retries had the same problem. Connection management had the same problem. Unnecessary repeated calls had the same problem. If an application makes five remote calls when it could have made three, there is nothing the server can do to make those other two disappear from the application's latency. That sounds obvious when written down. In a large system, it is surprisingly easy to lose sight of it because the client and server are usually owned by different teams looking at different telemetry. We Could Have Just Fixed That Client Initially, that was the straightforward option: talk to the application team, point out which calls should be parallelized, review the retry behavior, fix the implementation, and move on. There was nothing technically wrong with doing that. The problem was that it fixed exactly one consumer. We had multiple internal applications using this service. Over time, each team had learned some version of the integration rules: Use these timeouts.Retry this category of failures.Don't retry that category.Make these requests in parallel.Reuse connections.Avoid this unnecessary lookup.Handle this response differently Some teams followed nearly all of those rules. Some didn't. A new team could come along six months later and make a completely reasonable implementation that still missed two or three important details. I have seen this pattern in enough internal platforms that I don't particularly like relying on documentation as the primary mechanism for enforcing runtime behavior. Documentation is useful. It is not an execution environment. If something materially affects reliability or load on a platform service, I would rather encode it somewhere than repeatedly tell teams to remember it. A Client Library Was the Obvious Alternative The normal way to encode that behavior is a client library. Instead of letting every application make raw calls, the service team publishes a client: Java TenantClient client = TenantClient.create(config); Tenant tenant = client.lookup(tenantId); Inside the client, you can take care of details the application shouldn't have to think about: timeouts, retries, connection reuse, request shaping, parallelization, and error translation. For many services, I would stop here. A good client library is considerably simpler operationally than another process running beside every application. Our complication was that consumers weren't all written in the same language. Suppose the canonical client is implemented in Go. That is useful for Go consumers, but the Java services still need something. Then another runtime comes along and needs its own implementation. Before long, you can end up with something like: Plain Text Service | +-- Go client | +-- Java client | +-- Rust client | +-- another client Now you have several codebases that are all intended to express the same behavior. Maybe the new retry policy gets implemented in one codebase before the others. Maybe an application stays on an old SDK version because upgrading it also changes fifteen unrelated dependencies. Maybe one implementation handles an edge case differently. None of this makes client libraries bad. It just means that "we will maintain SDKs for every supported language and keep their behavior equivalent" is a real engineering commitment. In our case, there was another option: stop putting the intelligent client inside the application process. Moving the Integration Into a Sidecar The basic arrangement was simple. Instead of: Plain Text Application | | remote request v Internal Service We moved toward: Plain Text +-------------------------------------------+ | Application Instance | | | | +----------------+ | | | Application | | | +-------+--------+ | | | | | | local HTTP | | v | | +----------------+ | | | Sidecar | | | +-------+--------+ | +-----------|---------------------------------+ | | remote request v +--------------+ | Core Service | +--------------+ The application interacted with a loca The application interacted with a local HTTP interface. The sidecar contained the behavior required to communicate properly with the remote service. That distinction turned out to be much more useful than it might look from the diagram. The calling application no longer needed to contain all of the service-specific integration logic. From its perspective, the interaction became thin. The sidecar could take care of things such as retries, parallelization, error handling, and other optimizations that the service team understood better. It also gave us one implementation that could be used by applications written in different languages. A Java service could make the local call. So could a Go service. So could another runtime. The sidecar didn't care what language the business application used, and the application didn't care what language the sidecar was implemented in. That was the part we cared about. The Useful Part Was Ownership When people explain sidecars, they often start with deployment mechanics: two containers, same pod, localhost communication. All true. But that wasn't the reason I found this particular use case interesting. The real change was ownership. Previously, the boundary looked approximately like this: Service team: owns server implementation Application team: owns calling behavior, retries, concurrency choices, timeout choices, integration bugs With the sidecar, more of that shifted toward: Service team: owns server, owns sidecar, owns recommended client behavior Application team: calls a small local API This matters when a service is used widely. Say the service team discovers that a particular class of requests can be combined, or that a certain retry pattern behaves badly during partial degradation. With independently implemented clients, you may need multiple application teams to update multiple codebases. With the sidecar, the team that owns the service has somewhere to implement that knowledge directly. The useful property isn't "we have another container." It is "the people who understand the dependency best can control how the dependency is consumed." That is a very different reason for introducing a sidecar than simply wanting a fashionable Kubernetes architecture. Even a Well-Written Client Saw an Improvement One thing I liked about the rollout was that the benefit wasn't limited to the application that had originally complained. Another consumer was already doing a pretty good job. It followed the integration practices much more closely and saw latency of roughly 1 millisecond for the path being measured. After moving through the sidecar, that number was around 0.3 milliseconds — roughly a 70% reduction. I wouldn't generalize that number into "sidecars make services 70% faster." That would be a ridiculous conclusion. The result depended on that workload and on what the sidecar was doing. The interesting part was that even a reasonably optimized consumer still had room for improvement once the integration logic was owned and tuned in one place. We saw another effect too: fewer unnecessary requests reached the backend. That matters more as the number of consumers grows. If one client performs an unnecessary call, it is noise. If dozens of clients independently reproduce the same inefficient pattern, it becomes platform traffic. A shared implementation gives you leverage. Fix one behavior and every consumer using that path can benefit from it. What Retry Logic Looks Like Once You Own It Retries are a good example because they are easy to get mostly right and surprisingly easy to get badly wrong. You don't want thousands of sidecars retrying immediately, over and over, the moment a request fails. When the backend is already unhealthy, that turns clients into traffic amplifiers. Once retry behavior lives in a common component, you can define a policy around things such as maximum number of attempts, overall request deadline, retryable versus non-retryable failures, backoff, and jitter. Simplified pseudocode: Plain Text deadline = now + request_timeout for attempt in 1..max_attempts: response = call_service() if response.success: return response if response.is_not_retryable: return response if deadline_exceeded: fail sleep(backoff(attempt) + jitter()) I'm deliberately not presenting this as a production-ready retry algorithm. The point is that you now have one place where the policy exists. Without that, Team A may retry twice, Team B five times, Team C not at all, and Team D may have copied an example somebody wrote two years ago. That kind of variation is sometimes fine. For a heavily-used internal dependency, it may not be. Sidecars Also Create New Problems This is where I think discussions about sidecars sometimes become a little too enthusiastic. You are adding another process. If your application has 500 instances, you may now have 500 sidecars. If it has 2,000 instances, you may have 2,000 sidecars. That has consequences. Imagine, purely as an example, that a sidecar uses 50 MB of memory: Plain Text 50 MB x 1,000 instances = ~50 GB A 50 MB helper process sounds tiny when discussing one pod. It looks different after multiplying it across an entire fleet. The same applies to CPU. For a containerized application, an illustrative deployment could look something like this: YAML apiVersion: v1 kind: Pod metadata: name: sample-service spec: containers: - name: application image: sample-service:1.0 env: - name: TENANT_API value: "http://localhost:8081" - name: tenant-sidecar image: tenant-sidecar:1.0 ports: - containerPort: 8081 resources: requests: cpu: "50m" memory: "64Mi" limits: cpu: "200m" memory: "128Mi" Those resource values are illustrative, not values from the system I'm describing. The important point is that I would treat the sidecar as real production software, with explicit resource accounting, rather than as a free helper that happens to live beside the application. There Is Another Failure Boundary Now Before introducing the sidecar: Plain Text Application -> Service After introducing it: Plain Text Application -> Sidecar -> Service The extra layer solves one class of problems and introduces another class. What if the application is healthy, the backend service is healthy, but the sidecar isn't? From the application's point of view, the dependency is still broken. Startup and shutdown also require thought. The application shouldn't start handling traffic if it depends on a sidecar that isn't ready yet. During shutdown, you don't want the sidecar disappearing while the main application is still finishing requests. And then there is debugging. A request that previously had two obvious places to inspect now has three. If an application says a tenant lookup failed, somebody needs to determine whether the application reached the sidecar, whether the sidecar accepted the request, whether the sidecar called the backend, whether the backend timed out, whether the sidecar retried, whether the retry failed, or whether the response was rejected locally. This isn't an argument against the pattern. It is just the operational bill that arrives with it. If we are going to add another hop, even a local one, I want trace IDs or request IDs propagated through it and logs that let me reconstruct the path without spending an afternoon grepping unrelated timestamps. That sounds mundane, but these are the details that determine whether an abstraction feels helpful at 2 PM and terrible at 2 AM. Sidecar vs. Client Library I don't think there is a universal rule here. If you have three Java applications calling a straightforward service and the integration logic is tiny, I would probably build a Java client library and move on. Running another process per application instance just to avoid ten lines of client code would be architectural theater. A sidecar starts becoming much more interesting when several of these are true: Many applications use the same dependency.Those applications use different languages.The integration logic is more complicated than constructing an HTTP request.Retries, concurrency, caching, batching, or connection behavior materially affect the backend.Client behavior changes as the service evolves.The service-owning team needs more control over how clients interact with it. At that point, what you call the "client" may already be a small distributed-systems component. Giving it its own process and lifecycle starts to make more sense. The trade is still real. With an SDK, you have dependency-version and language-maintenance problems. With a sidecar, you have deployment, resource, lifecycle, and observability problems. You are choosing which complexity you would rather own. This Pattern Shows Up in Other Places Too The same reasoning is why sidecars have historically been useful for things such as observability. An application can write logs or metrics locally, hand them to a collector, and let that collector forward them to a telemetry backend. The business application doesn't need all of the batching, buffering, formatting, and delivery behavior embedded in its own code. Logging agents, metrics collectors, proxies, and other infrastructure helpers often fit naturally into this model for the same reason our internal client did: the capability needs to live close to the application, but it doesn't really belong to the application's business logic. What I Took Away From It The original complaint was basically, "this service is slow." It wasn't. Then the problem looked like a badly implemented client. That was closer, but fixing one client still wasn't the most useful outcome. What finally mattered was realizing that we were distributing service-specific expertise across application teams and then being surprised when those implementations behaved differently. Once you look at the problem that way, a sidecar isn't primarily a deployment trick. It is one way of deciding where knowledge should live. In this case, knowledge about retries, concurrency, request patterns, and other integration details belonged closer to the team operating the service than to every individual consumer. There is also a platform-engineering lesson here that I still find useful. A lot of teams talk about providing a "paved road" and then publish a long document telling everyone how to build the road themselves. I don't think that is much of a paved road. If there is one integration pattern that is safer, faster, and better understood, make that path easy to consume. Sometimes the answer is a good SDK. Sometimes it is an API gateway or proxy. And sometimes, when the client behavior is substantial enough, and the consumers are heterogeneous enough, a sidecar is the cleaner boundary. For us, that was the useful part of the pattern. Not the extra container. The fact that we could implement the tricky behavior once, put it under the ownership of the team that understood it, and stop asking every application to rediscover the same lessons.

By Saumya Tyagi
Detecting Requirement Drift in Automated Test Suites Through Content Hashing and Impact Analysis
Detecting Requirement Drift in Automated Test Suites Through Content Hashing and Impact Analysis

The Problem Mid-sprint, the product owner refines an acceptance criterion. The user story gets a new sentence. The automated suite doesn't notice. It keeps running the old assertions against the new requirement, and now you have two failure modes at once: tests that pass against behavior nobody wants anymore, and tests that fail against behavior the team deliberately changed. The usual response is to regenerate everything. That burns compute, buries real regressions under regenerated noise, and teaches the team to distrust the suite. The better answer is to know exactly which requirements moved and regenerate only the tests they touch. The Core Idea: The Requirement Is the Source of Truth Test automation goes stale because the suite has no memory of what it was testing. Each test was generated from some version of a requirement, but that version isn't recorded anywhere. When the requirement changes, nothing in the suite can tell you which tests are now wrong. The fix is a content hash. Hash the normalized text of the user story and its acceptance criteria, store the hash alongside the tests generated from it, and compare on every run. If the hash matches, the requirement hasn't moved, and the tests still apply. If it differs, something real changed, and only then do you regenerate. This is cheap and decisive. A SHA-256 of a few hundred words costs nothing, and the comparison is binary: same or different. No heuristics, no LLM judgment call about whether the edit was "significant." The hash decides. Hashing Design: Normalize Before You Hash Raw text hashing has one enemy: formatting noise. A reworded bullet, a reordered criterion, or an extra line break changes the hash without changing the meaning. So normalize first: strip whitespace, lowercase, sort the acceptance criteria, remove formatting artifacts. Hash the canonical form, not the editor's output. Granularity matters too. Hash at the story level and you regenerate every test for the story when one criterion changes. Hash at the criterion level and you regenerate only the tests tied to that criterion. Finer granularity costs more bookkeeping and saves more regeneration. For most teams, criterion-level hashing is the right trade. Store the hashes with the test metadata, not in a separate system that can drift on its own. The hash belongs next to the test it governs, versioned in the same repository. One more design point: hash the criteria, not the generated tests. Tests change for reasons that have nothing to do with requirements: refactors, framework upgrades, flakiness fixes. If you hash the test code itself, every refactor looks like drift. Hashing the requirement side keeps the signal clean. Only requirement changes should trigger regeneration. Impact Analysis: Limit Regeneration to Affected Tests Drift detection tells you what changed. Impact analysis tells you what it affects. You need a mapping from requirements to tests: a traceability record that says criterion C-7 is covered by tests T-12, T-13, and T-14. When C-7's hash changes, those three tests regenerate. The rest of the suite is untouched. The mapping also flows the other way. Shared fixtures, page objects, and helpers create dependencies between tests. If a changed criterion invalidates a shared helper, every test using that helper is affected even if its own criterion didn't move. A dependency graph over the test code turns a flat list of changed criteria into the real blast radius. Execution follows the same logic. There's no reason to run the full suite when three tests changed. Run the affected tests, then a smoke pass over the rest. Delta analysis on the requirements side and selective execution on the test side are the same principle applied twice. Code: Drift Detection and Impact Mapping The snippet below illustrates the core mechanism in Python: normalize and hash each criterion, compare against stored hashes, then resolve the affected tests through the traceability map. Treat it as a sketch of the structure, not a production module. Python import hashlib, json def normalize(text: str) -> str: """Canonical form: strip, lowercase, collapse whitespace.""" return " ".join(text.strip().lower().split()) def content_hash(text: str) -> str: return hashlib.sha256(normalize(text).encode()).hexdigest() def detect_drift(criteria: dict, stored: dict) -> list: """criteria: {criterion_id: text}. stored: {criterion_id: hash}. Returns the IDs whose requirement text actually changed.""" return [cid for cid, text in criteria.items() if content_hash(text) != stored.get(cid)] def affected_tests(changed: list, traceability: dict, dependencies: dict) -> set: """traceability: {criterion_id: [test_ids]}. dependencies: {test_id: [test_ids it shares helpers with]}.""" affected = set() for cid in changed: for tid in traceability.get(cid, []): affected.add(tid) affected.update(dependencies.get(tid, [])) return affected # Usage: only changed criteria trigger regeneration. changed = detect_drift(current_criteria, stored_hashes) if changed: to_regenerate = affected_tests(changed, traceability, test_dependencies) regenerate(to_regenerate) # only these stored_hashes.update({c: content_hash(current_criteria[c]) for c in changed}) else: run_suite_as_is() # nothing moved; nothing to rebuild The important lines are the last ones. Regeneration happens only when the hash comparison finds a real change, and it touches only the tests in the impact set. Everything else runs as-is. The requirement stays the source of truth because the suite literally cannot go stale without the hash noticing. Failure Modes: Where This Goes Wrong The first failure mode is hashing too much. If you include story metadata like sprint numbers or assignees in the hashed text, the hash changes every sprint and you regenerate constantly. Hash the requirement content only: the story text and the acceptance criteria. The second is stale traceability. The mapping from criteria to tests is only as good as its maintenance. If a new test is written without recording which criterion it covers, drift in that criterion won't regenerate it. Enforce the mapping at test-creation time, ideally in the same commit that adds the test. The third is semantic-but-identical drift. Sometimes a requirement changes meaning without changing the hashed text: a term gets redefined elsewhere, or a referenced spec updates. Content hashing can't see that. For those cases, keep a manual override that forces regeneration for a criterion, and use it during reviews of shared definitions. Operations: Making It Routine Run drift detection as part of the CI pipeline, not as a manual step. Every pull request that touches requirement documents should report which criteria changed and which tests will regenerate. That report is also a review artifact: it shows the product owner exactly what their edit costs. Track two metrics over time: regeneration rate (what fraction of the suite regenerates per sprint) and false-drift rate (regenerations triggered by formatting noise that normalization should have caught). If regeneration rate climbs, requirements are churning, and that's a planning signal. If false drift climbs, your normalization needs work. Make the drift report visible to the whole team, not just QA. When product owners see that a one-line edit regenerates twelve tests, they start writing more stable requirements. The hash becomes a quiet feedback mechanism that improves the requirements themselves. What I'd Do Again Hash the requirement, not the test. Normalize before hashing. Map criteria to tests and keep the map current. Regenerate only what moved, run only what's affected, and let the hash be the single decider. The requirement remains the source of truth, and the suite finally knows when it isn't.

By Shashank Shandilya
Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture
Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture

I spent six months replacing my own daily admin work with a small fleet of AI agents instead of writing about them. Three run in steady state; a fourth spins up on demand. Between them, they touch email, calendar, Slack, GitHub, a dozen SaaS APIs, a stack of PDFs, and a SQLite database I keep refusing to migrate. This is a field report on the engineering, written for the people who will actually have to build and operate this in production. The headline finding, for an audience of architects and engineers, is simple: the model is the cheap part. The work is everything downstream of it, and it looks far more like site reliability engineering than like AI research. The Model Stopped Being the Bottleneck I run roughly 600 euros a month across frontier models plus the agent layer. Adding another agent is a rounding error. I route most traffic to one provider and fall back to another on a bad day. By month two, the model was picking up context, calling tools, summarizing documents, and writing code well enough that it was no longer the limiting factor for anything I shipped. Model choice became an implementation detail behind an interface, the way you would treat any swappable dependency. That reframes the whole problem. If the model is a commodity capability behind a clean boundary, then the value and the risk both live in the system around it. The Seven Concerns That Are Actually Hard When I add a new agent, here is what I spend my time on. None of the frameworks I tried handle these to a production standard, so treat this as the reference architecture you build first. 1. Identity and least-privilege secrets. Every agent gets credentials scoped to exactly what it touches. If the email agent is compromised, the blast radius must stop there. This is standard service-account hygiene, applied per agent. 2. State management. Agents need durable, structured memory across days and weeks, not vector search over chat history. The real shape is operational state: the 18 active negotiations and their status, the document approved last Thursday, the record that changed on Monday. Building that was about 70 percent of the total work and broke most often. Model it like a domain database, not a transcript. 3. Write paths with safety. Read-only agents are toys. The moment an agent can mutate the outside world, you need idempotency keys, audit trails, rollback, and confirmation loops. These are the same primitives you would demand of any service that writes to production. The model does not give them to you. 4. Rate limiting and backoff against external tools. Not the model's rate limit. The downstream API's limit, including the 429 that gets returned as a body the model then happily parses as a success. Wrap every tool with explicit backoff and treat partial failures as first-class. 5. Retries with resumable state. If an agent fails on step 14 of a 20-step plan, it should resume, not restart. This is the durable-execution problem. A multi-step agent run is a workflow with checkpoints, not a single call. The pattern you want is closer to Temporal than to a request handler. 6. Observability with agent semantics. For every run, I capture the input, the model output, which tools were called, what they returned, and the final action. Stored, queryable, grep-able. Standard trace spans are not enough. You want to answer "which tool did the agent pick, and what did it expect to happen next?" 7. Escalation and kill switches. Every agent has an explicit "when to ask the human" rule and a channel to ask on. If I do not answer within two minutes, it stops and waits. And every agent has a literal off switch, not "redeploy after a fix." Cost and Prompt Drift Are Operational Risks, Not Setup Tasks Two failure modes deserve their own monitoring. Cost does not creep; it spikes. An agent running at 2 euros a day becomes 40 euros a day because it started looping on a tool error and nobody noticed. I run a daily digest of tokens per agent per task. Without it, I would be staring at a five-figure bill. Budget caps per agent, per task, per day, with auto-throttle on runaway loops, belong in your platform layer. Prompts rot. A prompt that was perfect at launch degrades over weeks as the model updates, the data shape shifts, or the task drifts into edges it never handled. I version every prompt and diff outputs on a sample set weekly. Treat prompts like code under test, or pay for treating them like stale documentation. Input is hostile. A document arrived last month with a prompt injection buried in the line items, instructing my agent to forward a contract to an external address. A paranoid parser caught it. Treat every external input as untrusted user input, because it is. The Build Order That Works Do not start with a framework. Start with the smallest, most annoying daily task that has a clean input and a clean output. Write a 60-line script. Plug a model into it. Watch it fail. Fix the failures. Only after you have shipped three of those and run them for a month without intervention should you reach for abstractions. The teams I see succeeding work this way. The teams that picked a framework first and went looking for a task are mostly still searching. The payoff is a compounding curve. Once the glue exists, each new agent is cheaper than the last. My first took three weeks. My fourth took two hours. If you remember one thing: "agentic" is much closer to a well-instrumented, long-running background job than to anything futuristic. Build the SRE layer first. The prompt is the last 20 percent. This piece is adapted from an essay first published at https://idofishman.ai/writing/agent-stack-six-months.

By Ido Fishman
Crash-Proof Agents: Durable Execution for Long-Running AI Systems
Crash-Proof Agents: Durable Execution for Long-Running AI Systems

Your Agent Is a Distributed System Wearing a Trench Coat Sometime this week, TrendForce reported that server CPU lead times stretched from 16-20 weeks to roughly 25-30 weeks, and the driver was not a new chatbot launch. It was agentic AI: workloads that stay alive for hours, holding state, invoking tools, orchestrating background work while a GPU does inference next door. The short interactive prompt-response session is giving way to persistent execution, and infrastructure planning is scrambling to catch up. Here is the uncomfortable part. Most agent code being written today assumes the machine it runs on will still be there in an hour. It assumes no deploy lands mid-run, no spot instance gets reclaimed, no pod gets evicted, no network partition eats an acknowledgment. Every one of those assumptions is false at scale, and we have known this for decades. The patterns that survive machine failure in distributed systems have names: write-ahead logs, checkpoints, idempotency keys, sagas. They work exactly as well for agents as they do for payment pipelines. They are just wearing different clothes. I spend my days at Google on Apigee Analytics and Monetization, running near-real-time API monitoring at roughly 440k transactions per second against 99.99% availability targets. When a box dies in my world, the run does not die with it. This article is the durable-execution playbook I would hand to a team building agents that run longer than a coffee break: why chat history is a fragile recovery medium, the three primitives that make execution durable, and the observability you need to operate it. Why Chat History Is a Fragile Save File The naive recovery strategy for an agent is to persist the conversation and replay it on restart. This fails in three specific ways. First, replaying thousands of tokens of conversation to remind the model where it left off is expensive and slow. You are paying inference cost to reconstruct position, and position is the cheapest thing in the system to store durably. A single integer — how many steps completed — replaces a context rebuild. Second, replayed context drifts. A model reading thirty steps of its own history can misinterpret what happened, especially if a tool output changed the plan mid-run. The log says what happened; the model infers what it thinks happened. Those are different things, and the gap is where bugs hide. Third, replay re-executes side effects. If step 14 called an API that charged a customer or provisioned infrastructure, a naive restart calls it again. This is the exact problem distributed systems solved with idempotency decades ago, and agents get it for free only if they are designed for it. The durable alternative: record progress as an explicit, structured log of events and checkpoints, and make recovery mean reading the log, not re-running the world. Primitive 1: The Write-Ahead Log and the Checkpoint The pattern is old and boring, which is why it works. Before a side effect happens, you write your intent to durable storage. After it completes, you write a checkpoint. Recovery means finding the last checkpoint and replaying only the unacknowledged tail. Temporal is the clearest articulation of this model: workflow code stays deterministic, activities are where side effects live, and a crashed worker resumes by replaying decisions from event history instead of re-executing them. LangGraph brings the same idea to the agent world with a checkpointer: pass one to compile(), and every superstep persists, keyed by thread_id. After a crash, invoking the graph with the same thread_id picks up at the last completed node rather than at the start. You do not need a framework to apply the pattern. Here is a compact, production-flavored implementation in Python using SQLite as the durable log. It is deliberately simple — one file, no services — because the logic is what matters, and you should be able to test every line of it. Python import json import sqlite3 import time import uuid from typing import Any, Callable, Optional class DurableStore: """Write-ahead log + checkpoint store backed by SQLite. The WAL journal mode means a crashed process never corrupts the log: a committed row is a committed row. """ def __init__(self, path: str): self._db = sqlite3.connect(path, timeout=30) self._db.execute("PRAGMA journal_mode=WAL") self._db.executescript( """ CREATE TABLE IF NOT EXISTS agent_log ( seq INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL, kind TEXT NOT NULL, -- 'intent' | 'checkpoint' payload TEXT NOT NULL, created_at REAL NOT NULL ); CREATE INDEX IF NOT EXISTS idx_agent_log_run ON agent_log(run_id, seq); """ ) def append(self, run_id: str, kind: str, payload: dict) -> int: cur = self._db.execute( "INSERT INTO agent_log (run_id, kind, payload, created_at)" " VALUES (?, ?, ?, ?)", (run_id, kind, json.dumps(payload), time.time()), ) self._db.commit() return cur.lastrowid def latest_checkpoint(self, run_id: str) -> Optional[dict]: row = self._db.execute( "SELECT payload FROM agent_log" " WHERE run_id = ? AND kind = 'checkpoint'" " ORDER BY seq DESC LIMIT 1", (run_id,), ).fetchone() return json.loads(row[0]) if row else None def unacked_intents(self, run_id: str, after_seq: int) -> list[dict]: """Intents logged after the last checkpoint with no completion.""" rows = self._db.execute( "SELECT payload FROM agent_log" " WHERE run_id = ? AND seq > ? AND kind = 'intent'" " ORDER BY seq", (run_id, after_seq), ).fetchall() return [json.loads(r[0]) for r in rows] Python class DurableRunner: def __init__(self, store: DurableStore, run_id: str): self._store = store self._run_id = run_id def run(self, steps: list[tuple[str, Callable[[], Any]]]) -> list[Any]: """Execute steps, resuming from the last checkpoint on restart. Each step is (idempotency_key, callable). A crash between the intent log and the checkpoint is safe: on resume, the step's idempotency key tells us whether it actually executed (see Primitive 2). """ checkpoint = self._store.latest_checkpoint(self._run_id) done = checkpoint["completed"] if checkpoint else 0 results: list[Any] = checkpoint["results"] if checkpoint else [] for i in range(done, len(steps)): key, action = steps[i] # 1. Write-ahead: log INTENT before the side effect. self._store.append(self._run_id, "intent", {"key": key, "step": i}) # 2. Execute. If this raises, the intent row stays unacked and # resume logic can reconcile it safely. result = action() results.append(result) # 3. Checkpoint: durable proof the step finished. self._store.append( self._run_id, "checkpoint", {"completed": i + 1, "results": results}, ) return results def new_run(store: DurableStore) -> str: run_id = f"run-{uuid.uuid4().hex[:12]}" store.append(run_id, "intent", {"key": "run-start", "step": -1}) return run_id Three things to notice. The intent row goes to disk before the side effect, so a crash can never leave you wondering whether the step was attempted — the log tells you, deterministically. The checkpoint stores results, not model context, so resume is a cheap database read rather than a context rebuild. And the results list is append-only history, which doubles as your audit trail for debugging. In my monitoring work, the equivalent insight is that you never reconstruct system state from metrics dashboards; you read the source-of-truth log. Primitive 2: Idempotency Keys on Every Tool Call The write-ahead log tells you a step was attempted. It does not tell you whether it succeeded. The killer case: the tool call executed, the process crashed before the checkpoint, and on resume you have an unacked intent for a side effect of unknown outcome. Retrying blindly can double-charge, double-provision, or double-notify. The fix is an idempotency key on every tool call, plus an executor that enforces at-most-once execution per key even across restarts. The key should be derived from the run and the step — for example, run_id plus step_index — never from a timestamp or a random value, because the resumed run must compute the identical key for the identical step. Go package durable import ( "context" "errors" "fmt" "math" "sync" "time" ) // Ledger is the durable record of completed tool calls, keyed by // idempotency key. Back it with Postgres, SQLite, anything that // survives the process. The interface keeps this testable. type Ledger interface { // Completed returns the stored result and true if key already ran. Completed(ctx context.Context, key string) (any, bool, error) // Record persists the result of a completed call. Must be atomic. Record(ctx context.Context, key string, result any) error } type Executor struct { ledger Ledger // inflight serializes concurrent Execute calls sharing one key. mu sync.Mutex inflight map[string]*call } type call struct { done chan struct{} result any err error } func NewExecutor(ledger Ledger) *Executor { return &Executor{ledger: ledger, inflight: map[string]*call{} } // Execute runs fn at most once per key. A duplicate key returns the // recorded result without re-running fn — this is what makes crash // recovery safe when the checkpoint write was lost. func (e *Executor) Execute(ctx context.Context, key string, fn func(context.Context) (any, error)) (any, error) { // Fast path: already completed in a previous attempt or process. if result, ok, err := e.ledger.Completed(ctx, key); err != nil { return nil, fmt.Errorf("ledger read for key %s: %w", key, err) } else if ok { return result, nil } e.mu.Lock() if c, exists := e.inflight[key]; exists { e.mu.Unlock() select { case <-ctx.Done(): return nil, ctx.Err() case <-c.done: return c.result, c.err } } c := &call{done: make(chan struct{})} e.inflight[key] = c e.mu.Unlock() c.result, c.err = e.withRetry(ctx, key, fn) e.mu.Lock() delete(e.inflight, key) e.mu.Unlock() close(c.done) return c.result, c.err } func (e *Executor) withRetry(ctx context.Context, key string, fn func(context.Context) (any, error)) (any, error) { const maxAttempts = 5 var lastErr error for attempt := 1; attempt <= maxAttempts; attempt++ { result, err := fn(ctx) if err == nil { // Record BEFORE returning: a crash after success but before // the record is the exact window the ledger exists to close. // If Record fails, the next attempt's Completed check may // return false and fn could run again — so Record must be // atomic and fn must itself be idempotent where possible. if rerr := e.ledger.Record(ctx, key, result); rerr != nil { return nil, fmt.Errorf("ledger record for key %s: %w", key, rerr) } return result, nil } lastErr = err if ctx.Err() != nil { return nil, ctx.Err() } backoff := time.Duration(math.Pow(2, float64(attempt-1))) * 200 * time.Millisecond select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(backoff): } } return nil, fmt.Errorf("key %s failed after %d attempts: %w", key, maxAttempts, lastErr) } var ErrDuplicateKey = errors.New("durable: duplicate idempotency key with different payload") The honest part of this code: there is always a tiny window — success happened, the record did not land — and no client-side trick closes it completely. The durable fix is to push idempotency to the server side (the tool API accepts the key and dedupes), which is why payment APIs all take idempotency keys. Client-side ledgers handle the common case; server-side keys handle the adversarial one. If your tools do not accept idempotency keys, add a reconciliation step on resume: before retrying an unacked intent, query the tool's current state to check whether the action took effect. That "check first, then act" step is the difference between a retry and a duplicate. Primitive 3: Sagas for Multi-Step Side Effects Checkpoints and idempotency make individual steps safe. But agents chain steps, and a failure at step 9 of 12 can leave steps 1-8 half-applied: a VM provisioned, a DNS record created, a ticket filed, and nobody to clean up. Retrying forward does not help when the plan itself is dead. You need compensations — each step paired with an undo action, executed in reverse order on failure. That is the saga pattern, and it is the standard answer in distributed transaction design. Python import logging from dataclasses import dataclass, field log = logging.getLogger("saga") @dataclass class SagaStep: name: str action: callable # forward action; raises on failure compensation: callable # undo; must be best-effort and idempotent @dataclass class Saga: steps: list[SagaStep] = field(default_factory=list) def add(self, name, action, compensation): self.steps.append(SagaStep(name, action, compensation)) return self # fluent chaining def run(self): completed: list[SagaStep] = [] for step in self.steps: try: log.info("saga: running step %s", step.name) step.action() except Exception as exc: log.error("saga: step %s failed (%s); compensating %d steps", step.name, exc, len(completed)) self._compensate(completed) raise completed.append(step) def _compensate(self, completed: list[SagaStep]) -> None: failures = [] for step in reversed(completed): try: log.info("saga: compensating step %s", step.name) step.compensation() except Exception as exc: # Never let a failed compensation mask the original error # or abort the remaining rollbacks. Record and continue. log.exception("saga: compensation for %s failed", step.name) failures.append((step.name, exc)) if failures: # Surface for human review: partial rollback is an incident, # not a silent success. raise SagaCompensationError(failures) class SagaCompensationError(Exception): pass Two rules make sagas work in practice. Compensations must be idempotent, because the compensation itself can crash midway and be retried — deleting a VM that is already deleted must be a no-op, not an error. And a failed compensation is an incident, not a bug to swallow: the saga raises so a human or an alerting path sees the partial rollback. In fifteen years of distributed systems work, I have never seen a rollback path that was tested as thoroughly as the forward path, and I have never seen a production incident that cared. Operating It: What to Measure Durable execution is not a library you drop in; it is a runtime property you operate. The metrics that matter: Checkpoint age and checkpoint lag. How far behind the durable log is the last checkpoint? A growing lag means your checkpoint writes are failing silently or your steps are too coarse. Alert on it the way you would alert on consumer lag in a queue.Resume count and replay cost. Every resume has a price: how many intents were reconciled, how many tool calls were deduped by the ledger, how many tokens were spent rebuilding context. If resume cost climbs, your steps are too long or your checkpoints too sparse.Unacked intent age. An intent row with no checkpoint after N minutes is either a stuck tool call or a crashed worker nobody noticed. This is your dead-man's switch.Compensation rate. How often sagas roll back. A rising rate is not a reliability problem — it is a planning problem. The agent's plans are failing more often, and that is a model or prompt issue, not an infrastructure one. And one operational practice that matters more than any metric: drain-aware deploys. Before replacing a worker, stop admitting new runs, let in-flight runs reach their next checkpoint, and only then shut down. The resume path should be ordinary work — a run continuing from its last checkpoint on a new machine — not an incident. Teams that run preemptible capacity already think this way; agent infrastructure needs the same discipline now that runs last hours instead of seconds. Build, Buy, or Borrow You do not have to hand-roll this. The landscape, honestly assessed: Temporal is the most complete answer for complex multi-step workflows: durable timers, signals for human-in-the-loop gates, replay-based recovery. The cost is operational — you run the Temporal cluster — and workflow code must be deterministic, which constrains how you write agent loops.LangGraph's checkpointer is the shortest path if you are already in the LangChain ecosystem: one argument to compile(), persistence keyed by thread. It checkpoints graph nodes, not arbitrary side effects, so pair it with idempotent tools.Restate and DBOS journal handler invocations with the database as the log. Good fit if your agents are structured as services rather than scripts.Airflow 3.3 recently moved its durability boundary from between tasks to inside a task, with an opt-in durable mode for AI agent steps that caches model responses and tool results so retries replay rather than re-pay. If your agents already live in Airflow, this is nearly free. My bias, from running high-throughput systems: start with the primitives, not the platform. A write-ahead log, idempotency keys, and checkpoint-on-completion cover 80% of crash scenarios with code you fully understand. Adopt a framework when your workflows need durable timers, human approval gates, or cross-service coordination — the point where hand-rolled state machines become the bug factory. The Boring Truth Nothing in this article is new. Write-ahead logging predates most agent frameworks by decades. Idempotency keys are how every payment API on earth survives retries. Sagas are textbook distributed transactions. The novelty is only in where the ideas are being applied: to systems that plan, act, and hold state for hours, built by teams that have never had to think about what happens when the machine disappears mid-thought. The agents that survive production will not be the smartest ones. They will be the ones that can crash at 3 AM, lose a machine, get deployed over, and resume from the last checkpoint as if nothing happened — because someone wrote the boring code that makes forgetting impossible. Be that someone.

By Khushan Adatiya

Culture and Methodologies

Agile

Career Development

Methodologies

Team Management

Detecting Requirement Drift in Automated Test Suites Through Content Hashing and Impact Analysis

November 20, 2026 by Shashank Shandilya

Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture

November 20, 2026 by Ido Fishman

Observability With AI SREs: A 4-Step Implementation Guide

November 20, 2026 by Frank Swain

Data Engineering

AI/ML

Big Data

Databases

IoT

Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent

November 23, 2026 by TAPASH BISHOI

Migrating From the OpenAI API to vLLM: Configure It Right

November 23, 2026 by Matt Sarrel

Designing a Multi-Region Kafka Cluster for Tier-0 Workloads

November 23, 2026 by Harini Rajendran

Software Design and Architecture

Cloud Architecture

Integration

Microservices

Performance

Building Enterprise Desktop, Web, Mobile, and Docker Applications From One Shared Platform

November 23, 2026 by Dariusz Małyszko

Migrating From the OpenAI API to vLLM: Configure It Right

November 23, 2026 by Matt Sarrel

Building a Self-Healing Docker CI Gatekeeper With BuildKit

November 23, 2026 by Siva sai krishna Suryadevara

Coding

Frameworks

Java

JavaScript

Languages

Tools

Migrating From the OpenAI API to vLLM: Configure It Right

November 23, 2026 by Matt Sarrel

Testing Async Code in Swift: Stop Using Task.yield() in Your Tests

November 23, 2026 by Nikita Vasilev

Building a Self-Healing Docker CI Gatekeeper With BuildKit

November 23, 2026 by Siva sai krishna Suryadevara

Testing, Deployment, and Maintenance

Deployment

DevOps and CI/CD

Maintenance

Monitoring and Observability

Building Enterprise Desktop, Web, Mobile, and Docker Applications From One Shared Platform

November 23, 2026 by Dariusz Małyszko

What Actually Costs You in a Production DevOps System

November 23, 2026 by Manvitha Potluri

Migrating From the OpenAI API to vLLM: Configure It Right

November 23, 2026 by Matt Sarrel

Popular

AI/ML

Java

JavaScript

Open Source

Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent

November 23, 2026 by TAPASH BISHOI

Getting Started With Weaviate: Building AI-Powered Search Applications With Java

November 23, 2026 by Otavio Santana DZone Core CORE

Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture

November 20, 2026 by Ido Fishman

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×