Event-Driven Distributed Points Settlement Engine: A Practical Guide
This article explains how to build an event-driven distributed settlement engine for virtual assets such as points, miles, and benefit quotas. It covers why a finite state machine (FSM) is a better fit than transaction scripts, how to express the state machine as a machine-readable specification, and how to implement the domain model, repository contracts, event-driven asynchronous processing, idempotency, optimistic locking, and observability. Readers will also find acceptance criteria and a phased rollout plan focused on two red lines: never miss a settlement and never get stuck.
1. Why Points Settlement Needs a State-Machine-Driven Engine
Points, miles, and benefit quotas are virtual assets. They look like simple addition and subtraction, but they are really an accounting system with strong consistency requirements. Three characteristics make them difficult:
- High volume and scattered sources. Purchases, returns, check-ins, and promotional grants all generate accounting requests.
- Continuously evolving business rules. Expiration, freezing, reversal, and cross-entity settlement keep piling up.
- Results must be verifiable. Any over-count or missed count turns directly into customer complaints and financial loss.
The traditional approach piles logic into transaction scripts with many if-else branches to decide the current stage. This is fast at first, but as rules grow, state checks scatter everywhere, and eventually nobody can explain which stages a given points entry went through.
A more robust approach is to model settlement as a finite state machine (FSM): a finite set of states, explicit transition conditions, and an immutable event emitted on every transition. The state machine is the business contract, the basis for testing, and the source for later automated code generation and validation rules.
Note that a system like this typically takes a senior engineer one to two weeks to design the skeleton. AI coding tools and specification-driven development can compress much of the repetitive and error-prone coding work, but architectural judgment still has to come from people.
2. Stage Zero: Write the State Machine as an Executable Contract
Before writing code, translate the state machine into a structured specification file. The value of a specification is that it is machine-readable: humans can review it, tools can validate it, and it can serve as input for code generation, which significantly reduces the chance of hallucinated implementations.
A minimal example of a settlement task entity and state definition:
entities:clearingTask:id: string # globally unique; a snowflake-style ID is recommendeduserId: stringamount: int # stored in the smallest unit to avoid floating-point errorscurrency: string # points type / benefit accountstate: enumversion: int # optimistic lock versionidempotencyKey: stringcreatedAt: timestampstateMachine:initial: INITstates:INIT: [ALLOWED, REJECTED]ALLOWED: [CLEARING, REJECTED]CLEARING: [SETTLED, RETRYABLE]RETRYABLE: [CLEARING, FAILED]SETTLED: []FAILED: [INIT]REJECTED: []invariants:- amount > 0- SETTLED is a terminal state and cannot transition further- the same idempotencyKey allows only one SETTLED
Three things matter most in the specification: terminal states must be declared explicitly; transitions must be unique and enumerable; invariants must be written as verifiable expressions. With this in place, illegal transitions surface at compile time or in unit tests instead of causing a production incident where an already-settled entry gets deducted again.
3. Stage One: Core Domain Model and Interface Contracts
The domain model should do only three things: define the aggregate root, define repository interfaces, and define domain events. The clearing task is the aggregate root, responsible for maintaining state and version. The repository interface exposes only three capabilities: query by ID and idempotency key, save, and conditional update. Domain events include task accepted, allowed, settled, and settlement failed but retryable.
The interface contract follows command-query separation. The write side accepts a settlement command and returns an acceptance result rather than the final accounting result; the query side provides a status tracking interface for front-end polling or later event subscription. This avoids long transactions blocking callers.
public interface ClearingTaskRepository {Optional<ClearingTask> findById(String id);Optional<ClearingTask> findByIdempotencyKey(String key);boolean saveIfAbsent(ClearingTask task);boolean compareAndSetState(String id, int expectVersion, ClearingState next);}
Amounts always use integer smallest units, and currency or points type is modeled explicitly. All timestamps are stored in a single unified time zone. These seemingly trivial constraints are the foundation for not missing any count later.
4. Stage Two: Event-Driven and Asynchronous Processing
Settlement should not synchronously wait for all downstream work to finish. The recommended approach is a local event table plus a message queue: the task state change and the event insert happen in the same local transaction, and a background dispatcher then reliably publishes the event to the message queue. This avoids distributed transactions while guaranteeing events are not lost.
Consumers route by event type: an allowed event updates quota reservation, a settled event calls the ledger to post the entry, and a failed event enters a retry queue with exponential backoff. To keep context changes across multiple files manageable, make consumers a thin layer that only does three things: deserialize, check idempotency, and call the domain service. Business complexity stays in the domain layer.
@EventListenerpublic void on(ClearingSettledEvent e) {if (eventLog.alreadyProcessed(e.eventId)) return;ledgerService.post(e.taskId(), e.amount());eventLog.markProcessed(e.eventId);}
For ordering, concurrent events for the same clearing task are routed to the same partition via consistent hashing, guaranteeing order within a single task; across tasks, parallelism is allowed to increase throughput.
5. Stage Three: Distributed Locks, Idempotency, and Concurrency Conflict Handling
Concurrency conflicts come from three places: duplicate delivery, duplicate requests, and state contention. There are three corresponding countermeasures.
First, put the idempotency key up front. All write interfaces must carry an idempotency key, the server enforces uniqueness with a unique index as a backstop, and duplicate requests return the first result directly.
Second, replace long transactions with optimistic locking. Use the version number for conditional updates, and on failure re-read and retry instead of holding a lock and waiting:
UPDATE clearing_taskSET state = 'CLEARING', version = version + 1WHERE id = ? AND version = ? AND state = 'ALLOWED';
Third, use distributed locks only for low-probability, strongly mutually exclusive sections, and always set a lease with renewal. After a lock times out, the state machine falls back to a retryable state to prevent getting stuck.
Observability is also part of concurrency handling: build monitoring and alerts for time spent in each state, retry counts, and dead-letter counts, so any backlog can be traced to a specific state and partition.
6. Acceptance Criteria and Rollout Plan
Acceptance revolves around two red lines. Never miss a count: reconciliation task coverage must be 100 percent, and the event table and ledger entries must be traceable in both directions. Never get stuck: any exception must reach a terminal or retryable state within a bounded time, with dead-letter handling and a manual intervention entry point configured.
The rollout is recommended in three steps: first use the specification and domain model to close the loop for a single task, then add event-driven and asynchronous consumption, and finally fill in idempotency, locks, and monitoring. Each step uses the state machine invariants as the core assertions of regression tests, keeping the evolution controllable and verifiable.
