Trading infrastructure · Reliability engineering · Distributed systems
TRADING SYSTEMS THAT SURVIVE FAILURE
Engineering Event-Driven Orders, Risk, and Deterministic Recovery
A lost acknowledgment is not a canceled order. A retried message is not necessarily a new trade. Under failure, correctness becomes the product.
Trading Infrastructure · Event-Driven Engineering
The exchange may fill an order before your system knows it exists.
TRADING SYSTEMS THAT SURVIVE FAILURE by Faramarz Kowsari approaches electronic trading as a distributed-systems correctness problem. A network timeout can leave an order's external outcome unknown; a duplicate event may arrive after a restart; a cancel and a fill can race; a system may report an apparently consistent position that disagrees with the exchange. These are not edge cases to hand-wave away after launch.
The manuscript follows Meridian, a deliberately fictional reference platform, to build the concepts needed for reliable order workflows: event contracts, durable identities, delivery semantics, safe retries, finite-state machines, FIX session/business distinctions, risk reservations, event sourcing, ledgers and reconciliation. It examines where guarantees end, especially the difference between internal message processing and external financial actions.
Beyond orders, the book addresses market-data sequence integrity, order-book reconstruction, latency measurement, stateful streams, leader election, split-brain prevention, deterministic historical reconstruction, operational observability, chaos drills, security and legacy-system migration. Its aim is not a glossy claim that failures disappear; it is a disciplined method for discovering what can go wrong and demonstrating safe behaviour at each boundary.
A closer look
A failure is a state transition, not a surprise
Three engineering questions that become urgent when the exchange and the application disagree.
Did the venue receive it?
A timeout leaves external status uncertain. Avoid automatic duplicate submission; use stable identity and reconciliation.
Is this the same execution?
Differentiate transport redelivery from new business events with event identity, idempotency keys and order-state invariants.
What can be safely resumed?
Rebuild verified state, reconcile positions and reservations, fence conflicting writers and resume only from an established boundary.
Meridian: a deliberately constrained teaching platform
The reference platform uses fictional instruments, accounts and venues to reason about event ordering, risk and recovery. The Go examples and simulator are educational abstractions; they are not exchange-certified trading software, a live venue adapter or proof of process-crash durability. That limitation is central to the book’s engineering honesty.
Inside the book
Technical depth beyond generic architecture diagrams
Order correctness
Finite-state machines, FIX sessions, cancel/replace races, late fills, busted trades and trade correction.
Risk and money movement
Concurrent reservations, atomic boundaries, sagas, ledgers, reconciliation and emergency controls.
Market-data correctness
Sequence gaps, order-book rebuilds, timestamps, clocks and delayed or stale state.
Operational reliability
Backpressure, bounded queues, latency tests, deterministic replay, chaos drills, failover, incident recovery and migration.
Correct event semantics
Model authoritative state, ordering, external effects and idempotent processing.
Orders that reconcile
Handle cancel/replace races, partial fills, late reports, correction and uncertain acknowledgment.
Exposure under concurrency
Engineer pre-trade checks, reservations, ledgers, kill switches and controlled failure behaviour.
Prove the restart path
Use replay, observability, fault injection, leader fencing and staged migration to test recovery.
A compact architecture map
How an order travels through an event-driven trading system
The book's fictional Meridian platform makes a deliberately uncomfortable fact visible: a local order instruction, a venue acknowledgment, and an effective financial execution are different kinds of evidence. Reliable software must preserve those differences across process and network boundaries.
Boundary that matters: a database transaction or broker transaction cannot roll back an external order that may already have reached a venue. The design needs a durable way to represent UNKNOWN_AT_VENUE instead of silently converting uncertainty into a second order.
The three identities engineers must not confuse
- Operation ID
- Identifies a business request, so a client retry does not create another independently authorized intent.
- Order ID / ClOrdID
- Identifies the logical order and, according to the relevant FIX or venue contract, its client-assigned external identity.
- Execution ID
- Identifies an effective fill within its venue-defined uniqueness scope; distinct partial fills must not be collapsed together.
- Transport event ID
- Identifies one message or event record, which is not automatically the same thing as the economic execution being reported.
Six failure cases · six different safety rules
What actually happens when the happy path breaks?
Each scenario below comes from a problem developed in the manuscript. These are hypothetical learning cases, not claims about a live exchange or verified commercial trading platform.
The venue may have received the order
A gateway writes to a socket, loses its connection and receives no business acknowledgment. The order might be live, even though the OMS has no confirmation.
Safe design: retain the original operation and client-order identity, mark the outcome unresolved, query the authoritative venue or broker evidence, and avoid blind resubmission.
Four reports do not necessarily mean four fills
An effective 40-unit execution is delivered repeatedly after a consumer restart; an independent 20-unit fill arrives later. The economically effective total is 60 units, not 180.
Safe design: maintain a durable execution inbox keyed to the venue's business identity and commit the deduplication decision with the financial ledger update.
Cancel requested is not canceled
For a 100-unit synthetic order, the system requests cancellation, then observes a valid 40-unit fill before final cancellation of the remainder.
Safe design: preserve the 40-unit economic effect, keep the remaining quantity at risk until cancellation is confirmed, and reconcile cumulative and leaves quantities.
Two approvals can overspend the same capacity
Two orders inspect the same apparent buying power before either records a reservation. Independent checks can both pass while their combined exposure violates a limit.
Safe design: enforce an atomic or equivalent authoritative reservation boundary, version the risk decision, and reject changed parameters that reuse an old authorization.
A fast but incomplete book is still invalid
A missed feed update makes reconstructed order-book state suspect. Continuing to generate book-dependent orders turns data incompleteness into execution risk.
Safe design: mark the affected book unsynchronized, recover a source-supported snapshot, align sequence anchors, and only then restore dependent decisions.
Two apparent leaders can both send orders
A paused old gateway wakes after a successor has obtained a newer ownership epoch. A lease alone does not necessarily prevent the old process from emitting a delayed order.
Safe design: fence stale writers at the point of external egress and reconcile uncertain orders before allowing the new owner to resume submissions.
Failure modes and the evidence that should settle them
| Failure | Unreliable shortcut | Stronger verification |
|---|---|---|
| Lost acknowledgment | Retry with a fresh order identifier | Durable intent plus authoritative venue inquiry |
| Duplicate fill report | Deduplicate only in volatile memory | Unique execution key and atomic financial posting |
| Cancel/fill race | Release risk on cancel request | Reconcile confirmed execution and leaves |
| Feed sequence gap | Continue using stale book state | Invalidity flag, gap repair and aligned snapshot |
| Gateway failover | Trust service-discovery leader status | Fencing at egress and single-sender evidence |
| Replay mismatch | Overwrite history to make charts agree | Fixed input corpus, versions, virtual clock and first-divergence analysis |
Chapter-by-chapter discovery
Explore the 50 Chapters
Open a thematic section to see the chapter register. The list below follows the structure and subject sequence of the book's source manuscript.
01Event-Driven Foundations
- Trading Systems Are Built Around Events
- Inside the Electronic Trading Lifecycle
- Correctness Before Speed
- Designing the Trading System's Event Architecture
- Requirements That Survive Production
02Messaging, Delivery and Idempotency
- Understanding the Messaging Landscape
- Designing Events That Can Be Trusted
- Partitioning, Ordering, and Parallel Processing
- Delivery Semantics Without Illusions
- Idempotency, Deduplication, and Safe Retries
- Backpressure During Market Stress
03Orders, FIX and State Reconstruction
- Orders as Finite-State Machines
- FIX Messages, Sessions, and Business State
- Cancel/Replace Races and Late Executions
- Fills, Corrections, and Trade Busts
- Event Sourcing for Trading Applications
- Projections, Consistency, and Concurrency
- Snapshots, Recovery, and Reconciliation
04Pre-Trade Risk and Financial Integrity
- Engineering the Pre-Trade Risk Gate
- Exposure, Reservations, and Concurrent Orders
- Transactions Across Service Boundaries
- Sagas and the Limits of Compensation
- Position Management and Financial Ledgers
- Kill Switches and Emergency Risk Controls
05Market Data and Execution Management
- Building a Market-Data Ingestion Layer
- Reconstructing the Electronic Order Book
- Sequence Gaps, Recovery, and Feed Integrity
- Instruments, Sessions, and Market Context
- From Market Events to Trading Decisions
- Execution Management and Smart Order Routing
06Latency, Clocks and Performance
- The Mathematics of Latency and Queues
- Networks, Kernels, and Message Transport
- CPU, Memory, and Runtime Behavior
- Clocks, Timestamps, and Causality
- Benchmarking Trading Systems Honestly
07Streams, Failover and Deterministic Recovery
- Stateful Stream Processing
- Stream Joins and Stale State
- Leader Election, Failover, and Split-Brain Prevention
- Poison Messages and Partial Failure
- Deterministic Replay and Historical Reconstruction
- Disaster Recovery and Trading Continuity
08Testing, Controls and Governance
- Testing the Trading State Machine
- Market Replay, Chaos Testing, and Production Drills
- Observability During Trading Hours
- Security and Operational Control
- Regulatory-Aware System Engineering
09Reference Implementation and Migration
- Designing the Reference Trading Platform
- Implementing the Order-to-Execution Pipeline
- Proving Reliability Under Failure
- Migrating Legacy Trading Systems Without Unsafe Cutover
From event log to defensible recovery
A deterministic recovery process must prove what it restores
An application can restart successfully while its financial state remains wrong. The book distinguishes service availability from business correctness and treats reconciliation as a release condition, not as an optional afterthought.
- Restrict external effects
Disable normal new-order egress and choose a documented safe operating mode while the external truth is uncertain.
- Establish authoritative ownership
Acquire a new gateway epoch and enforce a fence that excludes delayed writers from sending.
- Verify the recovery anchor
Load a consistent snapshot with recorded event cursor, schema/reducer version and integrity digest.
- Replay only the justified history
Use a fixed event corpus, configuration, reference data and virtual clock; keep outbound adapters inert.
- Reconstruct effective economics
Deduplicate executions, retain corrections and rebuild orders, positions and risk reservations.
- Reconcile the world outside
Query venue/broker working orders and executions; resolve or explicitly contain unconfirmed sends.
- Apply an accountable release gate
Require invariant checks and operational sign-off before resuming controlled new-order activity.
- Preserve diagnostic evidence
Record fault timing, source data, software versions, state hashes, outstanding exceptions and actions taken.
Eight invariants that give reliability claims a concrete meaning
- No unauthorized send: the risk decision must cover the exact operation, quantity, account and relevant terms.
- No double economic posting: the same effective venue execution cannot change position and cash more than once.
- No premature cancel relief: a request to cancel does not by itself eliminate executable remainder or release its reservation.
- No stale leader egress: a gateway with an obsolete ownership epoch cannot issue new orders.
- No unsynchronized-book decision: dependent strategies must not act on an order book whose feed state is unknown.
- No live side effects during replay: historical reconstruction routes proposed outbound actions to inert recorders.
- No orphaned uncertainty: every unresolved external send retains a durable inquiry or escalation owner.
- No erased corrections: effective ledger changes preserve the original execution observation and correction lineage.
A compact chapter-level example
One order, two fills, one pending cancellation
The manuscript uses fictional entities such as account AC-7, instrument SYN-A, venue SIM-X, order O-1001, and operation R-1001. A useful exercise is to trace a 100-unit order without allowing the OMS to mistake intention for external fact.
t0 OMS records order O-1001, quantity 100
t1 Gateway sends the order to fictional SIM-X
t2 Venue confirms working quantity 100
t3 OMS requests cancellation (still pending)
t4 Venue reports unique execution E-1: 40 units
t5 Venue confirms cancellation of remaining 60
t6 Ledger effective position: +40 units
t7 E-1 redelivered: zero additional economic effect
A design that releases all exposure at t3 is too optimistic. A design that applies E-1 twice at t7 is financially wrong. The example gives engineers two independent properties to test: respect for pending external state and idempotence of economic posting.
Five practical technical appendices
Reference material built for implementation reviews
Trading Event Schemas and Contracts
Identity scopes, event schema fields, command causation, version compatibility and carefully bounded Go examples. It distinguishes event_id, operation_id, order_id and execution_id.
Order State Machines and Invariants
Explicit states such as UNKNOWN_AT_VENUE, WORKING, PARTIALLY_FILLED, PENDING_CANCEL, and CANCELED, plus cancellation-race traces and safety assertions.
Failure-Injection and Recovery Playbook
Exercises for ambiguous acknowledgment, duplicate executions, market-data gaps, risk concurrency, outbox crashes, stale gateways, unsupported schemas and disaster failover.
Performance and Observability Reference
Worksheets for throughput, p50/p95/p99/p99.9 latency, unresolved-order age, feed gaps, queue age and replay state hashes, with measurement provenance rather than invented benchmark results.
Technical References and Domain Glossary
Definitions for FIX identifiers, idempotency, correction lineage, event sourcing, fencing tokens, deterministic replay and other terms that can carry incompatible meanings across vendors.
What the reference simulator establishes — and what it does not
The PDF describes a separate educational Go companion with ten reported in-memory tests, including a race-enabled test run. That evidence does not establish crash durability, live FIX connectivity, external venue reconciliation or production certification. No simulator download is claimed on this page.
Choose the part that matches your engineering problem
A guided path across the book's nine parts
- Foundations (Chapters 1–5): understand what an event proves, distinguish commands from observations, and write acceptance criteria that survive production.
- Transport & delivery (6–11): examine ordering, partitions, event contracts, exactly-once scope, durable deduplication and backpressure during stressed markets.
- Orders & state (12–18): define lawful transitions, distinguish FIX sessions from business state, and reconstruct fills, corrections and order aggregates.
- Risk & accounting (19–24): build pre-trade authorization, manage concurrent reservations, reason about sagas and financial ledgers, and design kill-switch behavior.
- Market data & routing (25–30): restore order-book integrity after sequence gaps, model instrument/session context and control execution routing.
- Performance & clocks (31–35): measure latency across explicit boundaries, understand queueing and causality, and benchmark without concealing workload assumptions.
- Streams & recovery (36–41): handle stale joins and poison messages, fence leaders, reconstruct historical state and recover from a failure domain outage.
- Tests & controls (42–46): write state-machine tests, replay market events, inject faults, instrument operations and address security and regulatory scope.
- Reference design & migration (47–50): connect the fictional order-to-execution components, map invariants to evidence and plan legacy cutover without an unsafe transition.
A useful starting question: where can this system make an irreversible external change, and what evidence survives if the process dies just before or just after it?
Who This Book Is For
Software engineers, quantitative developers, OMS/EMS maintainers, distributed-systems architects, trading platform teams, technical risk specialists and senior developers working with stateful financial workflows. Familiarity with APIs, databases and networks is assumed.
Scope and care
The reference examples are synthetic educational systems, not production-certified trading infrastructure. Real venue connectivity, jurisdiction-specific compliance, business continuity and operational controls require additional engineering and qualified review. No claim of profitability is made.
Before you read
Frequently Asked Questions
Is this a guide to profitable trading strategies?
No. It studies the correctness and recovery of electronic trading infrastructure. It does not claim profitable signals, strategies or market returns.
What does an unknown exchange acknowledgment mean?
A timeout cannot prove whether the venue accepted an order. The book explains why the system needs durable identity, inquiry, and reconciliation instead of blind resubmission.
Can exactly-once Kafka processing guarantee exactly one exchange order?
No. Internal transport and transaction guarantees cannot make an irreversible external venue action part of the same atomic commit.
How should duplicate execution reports affect positions?
The same effective venue execution should not post an additional financial effect when redelivered. Distinct legitimate partial fills must still be recorded; conflicting reuse of an execution key must be investigated.
Why can a canceled order still have a fill?
Cancellation requests are not immediate proof of cancellation. A fill can occur while a cancel is pending or arrive late; reconciliation must preserve economic truth.
How does the book approach risk limits with multiple concurrent orders?
It examines pre-trade risk authorization, atomic or equivalent reservations, committed exposure, instrument metadata, and conservative behavior when exposure or system state is unknown.
What is deterministic replay used for?
A fixed event corpus, code and rule version, metadata, and virtual clock can help reproduce internal state transitions and locate divergence. Outbound trading adapters must be disabled, and external venue reconciliation is a separate check.
Does the book cover market-data gaps and order-book reconstruction?
Yes. Chapters 25–27 address feed ingestion, order-book state, sequence gaps, snapshot alignment, and the need to block decisions that depend on an unsynchronized book.
Is the companion Go simulator production-ready?
No. The manuscript describes a separately supplied educational, in-memory Go simulator and local tests; it does not establish database crash durability, live FIX venue connectivity, or production certification.
What are the five technical appendices?
They cover event schemas and contracts, order state machines and invariants, failure-injection and recovery playbooks, performance and observability worksheets, and technical references plus a domain glossary.
See the Original Book Listing
Discover the book on Google Play Books, inspect the store information and open the available reader sample before deciding whether its approach matches your goals.
About Faramarz Kowsari
Faramarz Kowsari is an Istanbul-based author and researcher focusing on technology, education and personal growth. He has published over 160 digital titles across international platforms. His interests include artificial intelligence, prompt engineering, contemporary trading research, literature and mindfulness. He also develops web-based educational tools and specialized video content.
Official Website · Published Books · Author Profile · ORCID