BlogTank LabAboutContact
Work With Me
Notice

From now on we will use our new official domain thetanklog.com instead of tankbaclass.com.

Navigation
  • Blog
  • Tank Lab
  • About
  • Contact

© 2026 The Tank Log. All rights reserved.

Back to Articles/AI & Technology
AI & Technology

Vibe Coding and System Invariants

TM
Hoàng Tuấn Anh (Tank Mentor)
Lead Solution Architect
|
September 25, 2026
|
7 min read
|
1,175 reads
Vibe Coding and System Invariants

While AI excels at generating functional code and interfaces rapidly, it inherently lacks awareness of non-negotiable system constraints. Internalizing and verifying System Invariants is essential for safeguarding data integrity in production.

Vibe Coding and System Invariants: Establishing Architectural Guardrails with AI

In the previous article on Vibe Coding, I discussed the significant chasm between quick personal prototypes and enterprise-grade production environments. AI can produce fluid user interfaces and functional code within minutes. However, when deployed into live operations, systems frequently suffer severe failures, corrupted data states, or irreconcilable business logic conflicts.

The root cause: Generative AI excels at constructing smooth surface-level workflows, but fundamentally lacks intrinsic awareness of non-negotiable operational boundaries—namely, System Invariants.

When Business Analysts, Product Managers, or Developers fail to grasp system invariants, it is remarkably easy to be deceived by a specification or codebase that looks deceptively complete while silently compromising system data integrity.


1. What Are System Invariants?

Fundamentally:

A System Invariant is a logical condition or data constraint that must remain strictly true at all times, across every state of the system, regardless of concurrent user traffic or underlying network failures.

Business workflows adapt to changing market requirements, but system invariants remain immutable architectural rules.

In enterprise software engineering, four classical invariant families demand constant vigilance:

1. Invariants of Value and Financial Accounting (Conservation of Value) Total debits must strictly equal total credits at every instance. Capital cannot spontaneously materialize or vanish from a system.

A baseline transactional formula must be inviolable: Total Payment = Merchandise Subtotal - Discounts + Shipping Fee + Tax

If any edge case shifts this balance by even a single currency unit, financial integrity is broken.

2. Invariants of Inventory and Logistics (Non-Negativity) Available inventory and physical stock within database records must never evaluate to a negative value.

Physical assets in reality are strictly finite. When customer order volume exceeds available inventory, the system must immediately reject the request and inform the user.

To manage high concurrency during checkout, resilient systems implement an Inventory Reservation mechanism: temporarily holding the requested units for a constrained window (e.g., 10 minutes). If checkout is not completed before timeout, the units are immediately released back to available inventory.

When two concurrent users attempt to purchase the single remaining unit at the exact same millisecond, the system must guarantee that only one succeeds.

Note on Backorders & Pre-orders: Enterprise platforms (such as Amazon and Apple) do allow customer orders when immediate stock is exhausted (Backorder/Pre-order) to trigger procurement pipelines and prioritize allocation. However, invariants remain rigorously preserved: the system strictly segregates physical available inventory from backordered allocations, never allowing synthetic negative stock to misrepresent operational reality.

3. Invariants of Lifecycle Progression (Acyclic State Progression) The lifecycle of core domain entities (Orders, Invoices, Support Tickets) represents a Directed Acyclic Graph (DAG)—a one-way state progression.

Once an order transitions to a terminal state such as CANCELLED or COMPLETED, it cannot revert to PROCESSING. Any subsequent operational adjustment requires initiating a distinct workflow (such as creating a new order or issuing a refund credit memo), rather than mutating historic state.

Note: When product teams design backward state regressions—such as reopening cancelled orders instead of issuing new ones—downstream domain invariants collapse: released inventory may have already been sold, processed refunds cannot be clawed back automatically, and historic ledger reporting is invalidated.

4. Invariants of Data Relationships (Referential Integrity) An order line item (OrderItem) cannot exist without its parent entity (Order). Financial debit transactions must irrevocably bind to an authenticated customer identity.

Deleting parent records while leaving child records orphaned corrupts enterprise reporting across revenue, tax, and inventory dimensions.


2. Case Study: How AI Violates System Invariants

Consider a concrete case study: prompting an AI to draft an enterprise-grade technical specification for "Updating Shipping Address Post-Checkout".

The AI generated an extensive, 500-line specification featuring:

  • A 5W1H execution framework with clear Definition of Done (DoD).
  • An Order State Eligibility Matrix.
  • Comprehensive Mermaid Activity Diagrams handling multiple branches.
  • An Entity-Relationship Diagram (ERD) with audit logging (order_address_change_log) and surcharge ledgers (shipping_fee_adjustment).
  • Standardized RESTful API contracts with complete JSON payloads and HTTP status codes.
  • Advanced infrastructure patterns: Distributed Redis Locking (SET NX EX 10), SQL Optimistic Locking (WHERE version = :expectedVersion), and Kafka Event Streaming (order.shipping_address.updated).

While the deliverable appears comprehensive on the surface, critical system invariant vulnerabilities remain:

1. Lock Expiration Preceding Payment Completion

  • AI Design: When an address modification triggers a shipping surcharge on online payments, the system grants the user a 15-minute payment window. However, at the distributed lock layer, the AI configured a Redis Lock with a Time-To-Live (TTL) of only 10 seconds (SET lock:order:{orderId} <request_id> NX EX 10).

  • Production Impact: A user takes 60–90 seconds to scan a banking QR code. After 10 seconds, the Redis lock expires. Simultaneously, a warehouse operator scans the order barcode into PACKING.

    Two minutes later, the payment webhook confirms the surcharge. The backend attempts to mutate the address, but the database rejects the write because the order has progressed to packing. The customer was charged, but the package ships to the old address—creating an orphaned surcharge with no automated reconciliation.

2. Breaking Inventory Conservation During Warehouse Re-allocation

  • AI Design: If the new destination requires dispatch from an alternative fulfillment center, the AI designed a sequential workflow: (1) Check stock at New Warehouse -> (2) Verify availability -> (3) Release allocation at Old Warehouse and reserve at New Warehouse.

  • Production Impact: This represents a classic Check-Then-Act anti-pattern lacking atomic reservation.

    If the new warehouse has exactly one unit remaining, the moment the old reservation is released, a concurrent buyer purchases that last unit.

    When the reallocation request hits the new warehouse, it is rejected due to stockout. The order loses allocation across both facilities, stranding the order in an unfulfillable stock outage.

3. Financial, Promotional, and Tax Invariant Invalidation

  • AI Design: The AI calculated surcharge amounts via naive arithmetic: fee_difference = new_shipping_fee - old_shipping_fee.

  • Production Impact: This overlooks e-commerce promotional subsidy structures. The initial order may have utilized platform-subsidized shipping. If the address switch changes third-party logistics (3PL) partners where subsidies are invalid, who absorbs the deficit?

    Furthermore, freight is subject to VAT. For corporate accounts where electronic tax invoices (E-Invoices) have already been issued, changing the gross transaction value legally mandates an official Credit Note / Adjustment Invoice. The AI-generated schema contained zero attributes for tax tracking or regulatory compliance.

4. Dual-Write Anomalies and Missing Transactional Outbox

  • AI Design: Database transaction updates address -> Redis Lock released -> Event published directly to Kafka topic order.shipping_address.updated for WMS and logistics consumption.

  • Production Impact: A classic distributed dual-write failure. If the database commit succeeds but a network partition or container restart interrupts the Kafka publish, the event is permanently lost.

    The database records the new destination, but warehouse dispatch systems continue printing waybills with the old address. Preserving distributed invariants mandates a Transactional Outbox: persisting the event within the same database transaction before relaying to Kafka.

5. Idempotency Illusion

  • AI Design: The AI included an idempotency_key in the API request headers to mimic enterprise architecture.

  • Production Impact: In the underlying database schema, none of the tables (orders, order_address_change_log, shipping_fee_adjustment) persisted this key, nor was a UNIQUE INDEX defined.

    When transient network latency causes client retries or duplicate webhook delivery, no database constraint prevents duplicate surcharge records from executing.

Key Takeaway: In this scenario, the AI operated on a single prompt devoid of broader system context and architectural dependencies, making edge-case omissions expected. Nevertheless, this illustrates a critical reality: AI can replicate professional documentation syntax and diagrams with ease, but fundamentally lacks intrinsic understanding of Boundary States, Concurrency, and Distributed Invariants. Without human-driven architectural constraints, systems will inevitably degrade under production loads.


3. Establishing Guardrails When Working With AI

To govern AI collaboration effectively and avoid surface-level illusions, adopt this structured three-step protocol:

1. Pre-Define Requirements and Invariants in Prompts Before opening an IDE or prompting an AI agent to architect a feature, explicitly establish: What conditions must NEVER fail in this domain?

Articulate 3 to 5 non-negotiable invariant propositions:

  • "Available inventory must never evaluate to less than zero."
  • "Shipping addresses can only be modified when the order is strictly in PENDING state."
  • "Any change affecting shipping fees must trigger a successful settlement or refund before order state mutation is committed."

System invariants represent foundational requirements. Supplying these upfront equips AI with explicit boundaries, yielding substantially more resilient architectures.

2. Model State Transitions (Bridging Business and Engineering) When reviewing AI-generated specifications or code, rigorously scrutinize entity lifecycles.

Distinguish clearly between:

  • Business State Transitions (BA Perspective): Focused on customer and operational workflows (CREATED -> PAID -> PACKING -> DELIVERED / CANCELLED). Transitions occur upon valid business events.
  • Technical State Machines (Dev Perspective): Focused on transactional runtime mechanics, managing intermediate states, guard conditions, and distributed failure handling (concurrent double-submissions, network timeouts, payment gateway latency, idempotency, and rollbacks).

A common oversight when prompting AI is specifying only the Happy Path. AI inevitably generates designs optimized solely for that ideal flow. In production, systems break due to unhandled edge states.

Always interrogate transition points:

  • "What happens if this action is submitted concurrently from two separate clients in the same second?"
  • "If network drops mid-transition, what state does the system persist?"
  • "Can any execution branch violate the invariants established in Step 1?"

3. Establish Concrete Guardrails (Non-Tech & Developers)

Depending on your role, enforce guardrails at two distinct tiers:

For Non-Technical Stakeholders & Product Managers: Even without direct code or database access, you can establish powerful guardrails via specifications:

  • Specify Business Rules with Explicit Negations: Format rules strictly: IF [Condition], SYSTEM SHALL [Action] - MUST NEVER [Forbidden Action]. Avoid ambiguous language such as "handle flexibly".
  • Mandate Failure & Edge Case Matrices: Require AI to generate exhaustive tables: "List all potential failure modes, concurrency scenarios, and network partition states along with mandatory system responses". Convert this matrix into your Acceptance Criteria (Definition of Done - DoD).
  • Interrogate solutions with practical stress-test inquiries:
    • "If two customers purchase the last item simultaneously, who receives the order and who is declined?"
    • "If payment gateway confirmation is delayed, is customer balance debited while the order remains pending?"
    • "Once an order enters warehouse packing, is address modification disabled across client interfaces?"

For Developers & Solution Architects: Translate domain invariants into hard database and architectural constraints:

  • Enforce CHECK (quantity >= 0) to guarantee database-level rejection of negative stock anomalies.
  • Enforce FOREIGN KEY ... ON DELETE RESTRICT to eliminate orphaned child records.
  • Enforce UNIQUE (order_id, idempotency_key) to prevent duplicate execution during retries.
  • Encapsulate state mutations within explicit Database Transactions with appropriate isolation levels, combined with the Transactional Outbox pattern for asynchronous event publishing.

4. Conclusion

In software engineering, the distinction between disciplined systems thinking and superficial prompt execution centers on the ability to verify system invariants.

Engineers with systems thinking consistently identify non-negotiable system truths, proactively build guardrails to preserve data integrity, and take end-to-end accountability for production behavior. Conversely, relying solely on fluid UI demos or articulate AI documentation easily fosters a false sense of security.

AI serves as a powerful accelerator. However, critical thinking, architectural comprehension, and engineering discipline remain the decisive factors in building reliable, enterprise-grade software.

Chủ đề:#AI Mindset#Vibe Coding#System Invariants#Software Engineering#Architecture#Data Integrity
Chia sẻ bài viết này
Lan tỏa kiến thức thực chiến đến cộng đồng BA
TM
Hoàng Tuấn Anh (Tank Mentor)

Lead Solution Architect & BA Coach • 10+ năm kinh nghiệm thiết kế hệ thống

Work With Me
MỤC LỤC
5
Vibe Coding and System Invariants: Establishing Architectural Guardrails with AI1. What Are System Invariants?2. Case Study: How AI Violates System Invariants3. Establishing Guardrails When Working With AI4. Conclusion
CHỦ ĐỀ & THẺ
7
AI & Technology#AI Mindset#Vibe Coding#System Invariants#Software Engineering#Architecture#Data Integrity
0%