A Practical Guide to Building a Distributed Points Settlement Engine

    This article walks through a practical approach to building a distributed points settlement engine, focusing on four reliability requirements: no over-issuance, no missed tasks, no duplicate processing, and no deadlocks. It explains how to use spec-driven design to define a finite state machine and transition contracts, generate domain models and interface contracts, apply event-driven asynchronous processing, and handle distributed locks, idempotency, and concurrency conflict repair. It also covers layered stress testing and acceptance checks to validate correctness under peak traffic and failure scenarios.

    A Practical Guide to Building a Distributed Points Settlement Engine

    1. Why Settlement Engines Are a Hard Problem in Distributed Systems

    In scenarios such as e-commerce flash sales, loyalty points redemption, and financial benefit distribution, the traffic spike at midnight can push a large number of pending settlement tasks into the system at the same time. A settlement engine must hold four bottom lines at once:

    • No over-issuance: The total amount of points and benefits issued must strictly match the rules.
    • No missed tasks: Every eligible request must be processed, with no silent loss.
    • No duplicate processing: Results remain unique under network retries, message redelivery, and manual compensation.
    • No deadlocks: Asynchronous decoupling smooths out traffic peaks and prevents slow dependencies from dragging down the synchronous path.

    The traditional approach is for senior engineers to lead the effort, define the schema first, and then fill in the business logic, which usually takes more than two weeks. The path described in this article is different: first use a specification tool to lock down the state machine and contracts, then have AI coding tools take over modeling, asynchronous orchestration, and concurrency fixes in stages, compressing the delivery cycle into short, verifiable iterations.

    2. Step 1: Define the State Machine and Transition Contracts with Spec-Driven Design

    A settlement process is essentially a finite state machine. Every task must move along a legal path, and cross-state jumps are forbidden. The recommended set of states is:

    1. CREATED -> VALIDATING -> LOCKED -> COMPUTING -> SETTLED
    2. | \
    3. v v
    4. FAILED COMPENSATING -> SETTLED

    Transition constraints should be written as machine-readable specifications rather than scattered if checks in the code. An illustrative specification looks like this:

    1. entities:
    2. clearingTask:
    3. fields:
    4. taskId: string(unique)
    5. userId: string
    6. ruleVersion: string
    7. amount: int64(smallest unit)
    8. state: enum
    9. retryCount: int
    10. version: int64(optimistic lock)
    11. invariants:
    12. - amount >= 0
    13. - state transitions must conform to the transition table
    14. transitions:
    15. CREATED: [VALIDATING]
    16. VALIDATING: [LOCKED, FAILED]
    17. LOCKED: [COMPUTING, COMPENSATING]
    18. COMPUTING: [SETTLED, FAILED]
    19. FAILED: [COMPENSATING]
    20. COMPENSATING: [SETTLED]

    The value of a specification comes from three things: state transitions become a verifiable contract; field invariants are enforced when code is generated; and all subsequent implementations must pass contract tests, which prevents the implementation from drifting.

    3. Step 2: Generate Core Domain Models and Interface Contracts

    Once the contracts are stable, let AI coding tools lead the generation of domain models and interface skeletons. The goal is zero-hallucination output: all types, fields, and enums come from the specification, and the model is not allowed to improvise.

    Key actions include:

    1. Entities and value objects: Wrap amount, rule version, and state as immutable value objects to eliminate implicit type conversions.
    2. Repository interfaces: Define save / load / optimisticUpdate and push concurrency control down to the interface layer.
    3. Domain services: Keep settlement calculation, rule matching, and compensation strategies independent so each can be unit tested.
    4. Contract tests: Generate request/response samples and invalid-input cases for every interface, and make them fail before implementation.

    This stage does not touch the database or middleware. The output is a pure domain layer, and swapping the storage implementation later does not affect business semantics.

    4. Step 3: Event-Driven and Asynchronous Processing

    Refactoring context across multiple files and modules is the second area where AI coding tools help. The settlement flow is best split into three types of events:

    • Task events: task creation, validation passed, entering computation.
    • Result events: settlement succeeded, failed, entering compensation.
    • System events: lock timeout, retry limit reached, manual intervention.

    Key points for asynchronous processing:

    • Events carry an idempotency key: Use taskId + ruleVersion as the deduplication basis.
    • Explicit acknowledgment on the consumer side: Acknowledge only after successful processing; failures go to a retry queue with exponential backoff.
    • Local ordering guarantees: Route tasks for the same user to the same partition to avoid out-of-order processing.
    • Built-in observability: Every event carries a traceId that links production, consumption, and persistence across the full path.

    With event decoupling, the synchronous entry point only receives and persists requests, while consumers pull and perform the actual computation and issuance at their own capacity, which naturally smooths out traffic peaks.

    5. Step 4: Autonomous Repair of Distributed Locks, Idempotency, and Concurrency Conflicts

    The concurrency stage is where problems most often appear, and it is also where AI tools can perform autonomous repairs.

    1) Distributed locks
    A lock must have a lease and renewal to avoid deadlocks when the holder crashes. On release, verify the holder identity to prevent deleting someone else’s lock. Illustrative logic:

    1. tryLock(key, lease=3s, owner=traceId)
    2. -> business processing
    3. -> releaseIfOwner(key, owner)

    2) Idempotency
    All write operations go through an “idempotency table + unique constraint”: insert the idempotency record first, and treat a conflict as already processed and return the existing result. Amount updates use an optimistic lock version number, and conflicts trigger a re-read and retry rather than an unconditional overwrite.

    3) Autonomous conflict repair
    Let the tool locate failures from failing test cases automatically: lock not renewed, missing idempotency key, cross-state transition, amount precision loss. The repair loop is “reproduce the case -> minimal patch -> contract test regression”, and every round must be backed by tests to avoid fixing one issue and breaking three others.

    6. Stress Testing and Acceptance: Pushing the Engine to Its Limits

    Stress testing is not about looking at QPS numbers; it is about verifying the stability of the four bottom lines:

    • Over-issuance detection: Submit the same task concurrently N times, and the final issued amount must equal exactly one unit.
    • Missed-task detection: Inject consumer failures and redelivery, and verify 100% terminal-state coverage of tasks.
    • Duplicate detection: Artificially create network retries and confirm the idempotency table has no duplicate valid records.
    • Deadlock detection: Under slow-dependency injection, entry response time stays stable and queue backlog drains in a controlled way.

    A layered stress testing approach is recommended: start with single-module benchmarks, then apply gradual load across the full path, and finally run failure drills (node crashes, lock timeouts, message backlog). Record traceId-level details at each layer to make retrospective analysis easier.

    7. Summary

    The reliability of a distributed points settlement engine does not come from writing more code; it comes from contracts first, state convergence, asynchronous decoupling, and idempotency as a safety net. Use spec-driven design to lock down the state machine, domain modeling to isolate business semantics, event-driven design to absorb traffic spikes, and locks plus idempotency to preserve correctness. Then validate continuously with codified stress test cases. This approach can be adopted by a team and can also significantly shorten the delivery cycle with the help of AI coding tools, making it an engineering pattern worth reusing in e-commerce and financial-grade scenarios.