Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Verifiable Microservice Delivery in the AI Era: Contracts, Outbox & Fault Injection

This article demonstrates how to maintain verifiable microservice delivery in the AI coding era by establishing task contracts, state machines, transactional outbox patterns, business idempotency, and fault injection testing, using order timeout cancellation as a concrete example to address distributed system failure semantics and recovery protocols.

Introduction: AI-Generated Code Is Not Enough

AI can generate controllers, SQL, Kafka consumers, and unit tests in minutes. However, it does not automatically know critical distributed-system decisions: which service has final authority over order cancellation versus payment callback, whether a message send timeout permits a retry, or how to avoid duplicate inventory replenishment when the inventory service crashes after a database commit. These are not prompt-engineering gaps; they are the factual boundaries, failure semantics, and recovery protocols of distributed systems. The goal is not to restrict AI programming but to ensure every high-risk change involving AI comes with auditable, testable, and observable delivery evidence.

Applicable Scope

Java 17, Spring Boot 3.x, MySQL 5.7 InnoDB, Kafka. The code shows protocol skeletons; production deployment still requires validation with actual drivers, framework versions, capacity plans, and operational strategies.

Conclusion First: High-Risk AI Changes Must Deliver More Than Code

For changes touching orders, payments, inventory, or accounts, a merge request must include five categories of evidence:

Business Contract — Who owns the facts? What state transitions are allowed? Minimum form: invariants and state-transition table.

Implementation Boundary — What is allowed inside the local transaction? Minimum form: module dependencies and key SQL.

Recovery Protocol — How does the system converge after crashes, timeouts, and retries? Minimum form: Outbox / Inbox / idempotency design.

Verification Evidence — Why are critical failure windows covered? Minimum form: fault-injection tests and assertions.

Runtime Evidence — How does production detect non-convergence? Minimum form: backlog, conflict, and recovery-latency metrics.

AI excels at accelerating implementation within given boundaries; it should not unilaterally decide fact sources, compensation rules, or risk thresholds without business authorization.

A "Seemingly Complete" Code Example — What Is Missing?

A common requirement: scan timeout unpaid orders, cancel the order, release inventory, and notify downstream.

@Transactional(rollbackFor = Exception.class)
public void cancelTimeoutOrders() {
    for (Order order : orderMapper.findExpired(1000)) {
        RLock lock = redisson.getLock("cancel:" + order.getOrderNo());
        lock.lock();
        try {
            orderMapper.markCancelled(order.getOrderNo());
            stockCounter(order.getSkuId()).addAndGet(order.getQuantity());
            kafkaTemplate.send("order-cancelled", order.getOrderNo(),
                    serialize(order)).get();
        } catch (Exception e) {
            log.error("cancel failed", e);
        } finally {
            lock.unlock();
        }
    }
}

Transactions, locks, and logs appearing together still do not make three resources a single atomic operation. The real review must focus on failure windows:

Cancel update vs. payment callback concurrent — Both try to modify the order; later write overwrites earlier. Needed design: conditional state transition.

Redis replenish after transaction rollback — Inventory side-effect completes first. Result: order payable, inventory already released. Needed design: inventory local state machine.

Kafka success then database failure — Event seen by downstream first. Result: propagating a non-existent fact. Needed design: local Outbox.

Database commit then process exit — Message not yet sent. Result: cancellation notification permanently lost. Needed design: recoverable delivery.

Offset commit before consumer exit — Database already committed. Result: message will be re-consumed. Needed design: business idempotency.

Lock lease expiry — Old executor still running. Result: two executors both send messages. Needed design: token + consumer idempotency.

Some common judgments are not rigorous: catching an exception does not prove the transaction proxy didn't start; a consistent read seeing a historical committed version is not a dirty read; a long transaction extends connection occupancy but cannot alone prove pool exhaustion. Engineering review must start from reproducible timing and constrained state changes, not from annotations, locks, or keywords.

Let AI Read the Contract First, Then Write a Candidate Implementation

The correct workflow is not "requirements → AI code → merge" but a closed loop:

Feedback rules & metrics

Business requirements

Task contract

AI candidate implementation

Human review of key decisions

Architecture gates & fault tests

Canary, monitoring, recovery drills

Production evidence

The task contract serves as both model input and the shared basis for testing and review. Example contract (YAML):

objective: 取消到期且仍未支付的订单
source_of_truth:
  order: 订单库
  reservation: 库存服务的预留库
invariants:
  - 同一订单不能同时成功进入 PAID 和 CANCELLED
  - CANCELLED 与 OrderCancelled 必须在同一本地事务落库
  - 同一 reservationId 最多成功释放一次
failure_semantics:
  - Kafka 发送超时按结果未知处理,允许同一 eventId 重发
  - 库存事务提交成功后才能提交 offset
  - 重试耗尽后必须进入可查询、可人工接管的队列
constraints:
  - 数据库事务内不得调用 Redis、Kafka 或外部 RPC
acceptance:
  - 覆盖付款并发、提交后退出、重复投递、租约过期

If the source of reservationId, late-payment handling, or event-compatibility strategy are undecided, the AI's correct output is to expose the gaps, not to guess a "reasonable implementation."

Four Invariants: All Component Choices Start Here

1. Order State Only Decided by Conditional Migration

Cancellation and payment compete for the same order record:

UPDATE orders
SET status = 'CANCELLED',
    version = version + 1,
    cancelled_at = CURRENT_TIMESTAMP(3)
WHERE order_no = :orderNo
  AND status = 'UNPAID'
  AND expire_at <= CURRENT_TIMESTAMP(3);

Affected rows = 1 means cancellation succeeded; 0 means not expired, already paid, already cancelled, or non-existent — in all cases inventory must not be released. The payment path must also constrain the old state:

UPDATE orders
SET status = 'PAID', version = version + 1, paid_at = CURRENT_TIMESTAMP(3)
WHERE order_no = :orderNo AND status = 'UNPAID';

The order state machine only adjudicates facts in the order database. If the payment channel has already deducted funds but the callback arrives late, a successful cancellation cannot erase the external deduction; the late callback must enter a query, refund, or manual reconciliation queue.

2. Business Facts and Pending Events Must Be Persisted in the Same Transaction

Order cancellation and Outbox insertion share one data source, one connection, one transaction. ApplicationEventPublisher and @TransactionalEventListener(AFTER_COMMIT) can wake the deliverer but are not persistent queues; the process can exit after commit but before the listener runs.

Outbox table schema:

CREATE TABLE order_outbox (
  event_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  order_no VARCHAR(64) NOT NULL,
  event_type VARCHAR(64) NOT NULL,
  order_version BIGINT NOT NULL,
  payload JSON NOT NULL,
  status VARCHAR(16) NOT NULL DEFAULT 'NEW',
  attempts INT NOT NULL DEFAULT 0,
  next_attempt_at DATETIME(3) NOT NULL,
  lease_token CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL,
  lease_until DATETIME(3) NULL,
  last_error VARCHAR(1024) NULL,
  created_at DATETIME(3) NOT NULL,
  sent_at DATETIME(3) NULL,
  PRIMARY KEY (event_id),
  UNIQUE KEY uk_transition (order_no, event_type, order_version),
  KEY idx_ready (status, next_attempt_at),
  KEY idx_lease (status, lease_until)
) ENGINE=InnoDB;
uk_transition

prevents duplicate creation of the same event type for the same order version. The message must be a fact snapshot containing at least eventId, order number, order version, full reservation list, occurrence timestamp, and schemaVersion; the consumer cannot infer what happened by reading the "current order."

3. Duplicate Delivery Must Not Repeatedly Change Business State

eventId

identifies a delivery for troubleshooting and generic Inbox deduplication; reservationId identifies an inventory reservation, ensuring the "release inventory" business effect occurs at most once. Kafka's exactly-once coordinates within Kafka scope; it cannot automatically include MySQL and Redis in the same atomic transaction.

4. Failure Must Have a Recoverable State

Failure cannot just leave logs: scan failures, Outbox backlog, inventory conflicts, and manual reconciliation must all have persistent records, failure reasons, next retry times, and assigned handlers. Deleting records and saying "handled" merely deletes the ability to recover.

Data Relationships and Transaction Boundaries

The order database needs not only orders and Outbox but also an immutable order-reservation relationship:

CREATE TABLE order_reservation (
  order_no VARCHAR(64) NOT NULL,
  reservation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  sku_id BIGINT NOT NULL,
  quantity INT NOT NULL,
  PRIMARY KEY (order_no, reservation_id),
  UNIQUE KEY uk_reservation (reservation_id)
) ENGINE=InnoDB;

ALTER TABLE orders ADD INDEX idx_timeout (status, expire_at, id);

This table records the reservation relationships created when entering the unpaid state; they are never rewritten. The cancellation event carries the reservation IDs; the inventory service still uses its own reservation table as the authoritative source for SKU and quantity.

@Transactional(rollbackFor = Exception.class, timeout = 3)
public boolean cancelIfExpired(String orderNo) {
    if (orders.cancelIfUnpaidAndExpired(orderNo) != 1) {
        return false;
    }
    Order order = orders.loadCancellation(orderNo);
    List<OrderReservation> items = reservations.findImmutableByOrderNo(orderNo);
    outbox.insert(OrderCancelledEvent.from(order, items));
    return true;
}

Preconditions: the three repositories bind to the same transaction manager; Outbox write is not asynchronous; insertion failure must throw; the call goes through the Spring transaction proxy to avoid self-invocation bypass. timeout = 3 is only an example budget; connection acquisition, SQL execution, and scheduling should each have separate limits.

The scanner uses stable pagination on (expire_at, id) with a fixed expiry upper bound per round. Do not persist a cursor that only moves forward, otherwise smaller-ID orders expiring later may be permanently skipped. Each round should have limits on count, total time, and concurrency; index effectiveness still requires execution-plan and lock-wait analysis under target data volumes.

Complete Outbox State Protocol

Outbox is not "insert a table and scan periodically." The deliverer must have explicit states and token-protected write-back rules:

NEW → (conditional preempt / leaseToken) → SENDING → (Kafka ack & token match) → SENT

SENDING → (retryable failure & token match) → RETRY

SENDING → (lease expiry) → NEW (other deliverer takes over)

RETRY → (exceed retry budget) → DEAD → manual recovery

MySQL 5.7 can query candidate IDs then conditionally update each row to preempt, without SKIP LOCKED:

UPDATE order_outbox
SET status = 'SENDING',
    lease_token = :token,
    lease_until = DATE_ADD(CURRENT_TIMESTAMP(3), INTERVAL 30 SECOND),
    attempts = attempts + 1
WHERE event_id = :eventId
  AND ((status IN ('NEW','RETRY') AND next_attempt_at <= CURRENT_TIMESTAMP(3))
       OR (status = 'SENDING' AND lease_until < CURRENT_TIMESTAMP(3)));

Send only when affected rows = 1. On send confirmation:

UPDATE order_outbox
SET status = 'SENT', sent_at = CURRENT_TIMESTAMP(3), lease_until = NULL
WHERE event_id = :eventId
  AND status = 'SENDING'
  AND lease_token = :token;

On retryable failure, also write back with token to prevent old executor overwriting new lease:

UPDATE order_outbox
SET status = 'RETRY', lease_until = NULL,
    next_attempt_at = :nextAttemptAt, last_error = :error
WHERE event_id = :eventId
  AND status = 'SENDING'
  AND lease_token = :token;

Crash points and recovery results:

Before preempt or preempt transaction rollback → event still available for other deliverer.

Preempt committed, exit before send → lease expires, re-deliver.

Kafka received, exit before SENT → same eventId resent, consumer idempotent.

Old lease expires while still sending → possible duplicate send, but old token cannot overwrite new state.

Exceed retry budget → enter DEAD, retain reason, manual recovery.

Using order_no as Kafka key helps same-partition ordering, but parallel deliverers may let a newer version arrive before an older one. If strict version ordering is required, serialize delivery per aggregate or have the consumer reject/buffer discontinuous versions.

Inventory Service: Protect Inventory with a Reservation State Machine, Not Message Increments

The inventory service owns inventory_reservation. reservation_id is unique; states are RESERVED / CONFIRMED / RELEASED; SKU and quantity are immutable after creation. On consuming an event, lock the local reservation first, then decide the result:

@Transactional
public ReleaseResult release(String reservationId) {
    InventoryReservation r = reservationRepository.findByIdForUpdate(reservationId);
    if (r == null) return ReleaseResult.MISSING;
    if (r.status() == RELEASED) return ReleaseResult.DUPLICATE;
    if (r.status() == CONFIRMED) return ReleaseResult.CONFLICT;
    if (r.status() != RESERVED) return ReleaseResult.INVALID_STATE;

    if (reservationRepository.markReleased(reservationId) != 1) {
        throw new IllegalStateException("reservation changed unexpectedly");
    }
    if (stockRepository.increaseAvailable(r.skuId(), r.quantity()) != 1) {
        throw new IllegalStateException("stock row missing");
    }
    return ReleaseResult.RELEASED;
}

The critical read must be a transactional locking read:

SELECT reservation_id, sku_id, quantity, status
FROM inventory_reservation
WHERE reservation_id = :reservationId
FOR UPDATE;

Reading the reservation, state transition, and stock increase must occur in the same inventory database transaction. RELEASED means duplicate; CONFIRMED means business conflict; missing reservation requires distinction per creation protocol (out-of-order, data loss, or illegal event). Multi-SKU orders are processed in fixed SKU order and support full-transaction deadlock retry.

The consumer commits the offset only after the inventory transaction commits. If the process exits after commit but before offset, the message replays but the reservation is already RELEASED, so stock is not increased again. If the inventory service also publishes "release completed," it should use its own Outbox.

Late Payment, Out-of-Order, Schema Evolution: Cannot Decide in Production

Cancellation then receive payment success callback — Do not overwrite to PAID; query order then refund or manual reconciliation, keep audit trail.

Old version event arrives late — Do not overwrite new state; reject by aggregate version, idempotent handling, or compensation flow.

Message format adds field — Do not assume all consumers upgrade simultaneously; make consumers tolerate new fields first, then publish producer.

Field semantics change or delete — Do not reuse original field name; create versioned event or parallel topic, migrate then deprecate.

Redis only cache — Do not let cache decide inventory facts; use inventory DB as source, cache failure retry/invalidate.

Redis decides flash-sale admission — Do not just use INCRBY once; design deduplication, persistence, failover, and account reconstruction.

Turn Team Memory into Executable Gates

Rule files give AI context; CI actually blocks violations. ArchUnit example: ensure the order transaction package has no direct dependencies on middleware or remote clients.

@AnalyzeClasses(packages = "com.example.order")
class ArchitectureGuardTest {
    @ArchTest
    static final ArchRule tx_package_has_no_external_dependencies =
        noClasses().that().resideInAPackage("..application.tx..")
            .should().dependOnClassesThat().resideInAnyPackage(
                "..gateway..",
                "org.springframework.kafka..",
                "org.redisson..",
                "org.springframework.data.redis..",
                "feign..",
                "java.net..",
                "java.net.http..");
}

ArchUnit checks bytecode dependencies; it cannot automatically prove the full runtime call chain. Patterns like "transaction service → helper → HTTP", reflection, meta-annotations, and programmatic transactions still need port design, dependency graphs, and integration tests. CI should also enable empty-match failure to prevent rules from silently becoming ineffective.

AI Review output likewise needs structured evidence: location, fact, failure window, suggested verification, confidence. Repository text, issues, logs, and tool outputs may carry untrusted instructions; review tasks should use least privilege and avoid production credentials.

Use Fault Injection to Prove "Can Recover", Not Just "Runs"

Payment vs. cancellation concurrent — Barrier control two conditional updates starting simultaneously → only one state transition succeeds, failure side has no success event.

Outbox insert fails — Make repository throw exception → order update and Outbox roll back together.

Exit after commit — Terminate process in post-commit callback → restart, Outbox eventually delivered.

Exit after Kafka ack — Simulate termination after send ack → resend same eventId, inventory released only once.

Exit after inventory commit — Inject fault between DB commit and ack → replay, available stock not increased.

Lease expiry — Stop old deliverer, let new deliverer preempt → old token cannot write back, duplicates digestible.

Deadlock — Lock two SKUs in reverse order → whole transaction backs off and retries, inventory conserved.

Schema evolution — Run old and new consumers simultaneously → compatibility strategy matches contract.

Mockito suits branch verification; Testcontainers suits real database constraints and middleware interaction; neither replaces target-environment network and master-slave failure drills. Tests should assert order final state, Outbox records, event counts, reservation status, stock values, and manual queues — not just mock invocation counts.

Runtime: Monitor "Where Facts Haven't Converged"

At minimum, establish these metrics:

Timeout uncancelled order count, oldest expired order wait time.

Outbox oldest unsent event age, retry rate, lease reclaim count, DEAD count.

Inventory release conflicts, missing reservations, duplicate processing, manual queue backlog.

Database connection wait, transaction duration, lock wait, deadlock retries, executor rejections.

End-to-end recovery time from order cancellation commit to inventory final release.

Low Kafka lag may only mean events are still stuck in Outbox; therefore, create metrics for each persistent stage and define SLO by end-to-end recovery time. Async tasks should explicitly configure Executor, queue, concurrency budget, timeout, and rejection strategy. An unspecified CompletableFuture typically uses the common pool, whose behavior depends on JVM visible processors and configuration — do not over-infer from "Pod two cores."

Start Landing from One High-Risk Change

Week 1: For one order/payment/inventory chain, write authoritative data, state transitions, idempotency keys, and manual handling entry; add a minimal Outbox.

First iteration: Add architecture gates, four most critical fault-injection tests, Outbox backlog and recovery-time metrics; make consumers compatible with new schema first, then enable producer.

First quarter: Precipitate high-risk chain contracts, test templates, and review outputs into repository spec; for existing violations establish a baseline with owner and deadline; first prohibit new violations, then gradually remediate technical debt.

Measure AI programming benefits by high-risk defect detection rate, false-positive ratio, change failure rate, recovery time, and review time. Code generation volume and adoption rate only indicate usage frequency, not delivery reliability.

Conclusion

AI most easily delivers seemingly complete code; it most easily misses the protocols between code. For every distributed-system change, answer: who decides facts, what does failure leave, how are duplicates handled, how is recovery verified. Conditional state updates protect transitions, Outbox preserves todos, business idempotency limits side effects, architecture gates constrain boundaries, fault tests and monitoring prove recovery paths. These mechanisms are not AI replacements; they are precisely the prerequisites for teams to use AI at larger scale with more confidence.

References

Spring Framework: Declarative Transactions & Proxy Invocation

MySQL: InnoDB Consistent Non-Locking Reads

Spring Framework: TransactionalEventListener

Apache Kafka: Documentation and Design Semantics

Redisson: Locks and Synchronizers

ArchUnit User Guide

Java SE 17: CompletableFuture

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

distributed systemsmicroservicesAI-assisted developmentidempotencyfault injectiontransactional outbox

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion