TRADING SYSTEMS THAT SURVIVE FAILURE book cover by Faramarz Kowsari

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.

50 chapters · 9 engineering tracks · 5 technical appendicesEnglish-language edition

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.

Event-driven OMSFIX & stateIdempotencyRisk reservationsDeterministic replayFailover

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.

UNKNOWN

Did the venue receive it?

A timeout leaves external status uncertain. Avoid automatic duplicate submission; use stable identity and reconciliation.

DUPLICATE

Is this the same execution?

Differentiate transport redelivery from new business events with event identity, idempotency keys and order-state invariants.

RECOVER

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.

EVENT

Correct event semantics

Model authoritative state, ordering, external effects and idempotent processing.

ORDER

Orders that reconcile

Handle cancel/replace races, partial fills, late reports, correction and uncertain acknowledgment.

RISK

Exposure under concurrency

Engineer pre-trade checks, reservations, ledgers, kill switches and controlled failure behaviour.

RECOVER

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.

1. Strategy / client intentStable business operation key and validated order terms
2. Pre-trade risk gateAuthoritative authorization and bounded exposure reservation
3. OMS & durable intentTracked order state, persistence and idempotent admission
4. Fenced gatewayOne authorized outbound owner; stable client identity
5. Venue / brokerAccepted, rejected, filled, or still unknown from local evidence
Venue execution reportsPreserve source and correction lineage
Execution inboxDeduplicate unique economic effects atomically with posting
Ledger & positionsRecognize verified fills, reservations and corrections
Reconciliation & viewsCompare authoritative venue state with internal reconstruction

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.

Case 01 · Ambiguous acknowledgment

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.

Case 02 · Duplicate execution

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.

Case 03 · Cancel/fill race

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.

Case 04 · Concurrent risk requests

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.

Case 05 · Market-data sequence gap

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.

Case 06 · Split-brain gateway

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

FailureUnreliable shortcutStronger verification
Lost acknowledgmentRetry with a fresh order identifierDurable intent plus authoritative venue inquiry
Duplicate fill reportDeduplicate only in volatile memoryUnique execution key and atomic financial posting
Cancel/fill raceRelease risk on cancel requestReconcile confirmed execution and leaves
Feed sequence gapContinue using stale book stateInvalidity flag, gap repair and aligned snapshot
Gateway failoverTrust service-discovery leader statusFencing at egress and single-sender evidence
Replay mismatchOverwrite history to make charts agreeFixed 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 Foundations5 chapters
  1. Trading Systems Are Built Around Events
  2. Inside the Electronic Trading Lifecycle
  3. Correctness Before Speed
  4. Designing the Trading System's Event Architecture
  5. Requirements That Survive Production
02Messaging, Delivery and Idempotency6 chapters
  1. Understanding the Messaging Landscape
  2. Designing Events That Can Be Trusted
  3. Partitioning, Ordering, and Parallel Processing
  4. Delivery Semantics Without Illusions
  5. Idempotency, Deduplication, and Safe Retries
  6. Backpressure During Market Stress
03Orders, FIX and State Reconstruction7 chapters
  1. Orders as Finite-State Machines
  2. FIX Messages, Sessions, and Business State
  3. Cancel/Replace Races and Late Executions
  4. Fills, Corrections, and Trade Busts
  5. Event Sourcing for Trading Applications
  6. Projections, Consistency, and Concurrency
  7. Snapshots, Recovery, and Reconciliation
04Pre-Trade Risk and Financial Integrity6 chapters
  1. Engineering the Pre-Trade Risk Gate
  2. Exposure, Reservations, and Concurrent Orders
  3. Transactions Across Service Boundaries
  4. Sagas and the Limits of Compensation
  5. Position Management and Financial Ledgers
  6. Kill Switches and Emergency Risk Controls
05Market Data and Execution Management6 chapters
  1. Building a Market-Data Ingestion Layer
  2. Reconstructing the Electronic Order Book
  3. Sequence Gaps, Recovery, and Feed Integrity
  4. Instruments, Sessions, and Market Context
  5. From Market Events to Trading Decisions
  6. Execution Management and Smart Order Routing
06Latency, Clocks and Performance5 chapters
  1. The Mathematics of Latency and Queues
  2. Networks, Kernels, and Message Transport
  3. CPU, Memory, and Runtime Behavior
  4. Clocks, Timestamps, and Causality
  5. Benchmarking Trading Systems Honestly
07Streams, Failover and Deterministic Recovery6 chapters
  1. Stateful Stream Processing
  2. Stream Joins and Stale State
  3. Leader Election, Failover, and Split-Brain Prevention
  4. Poison Messages and Partial Failure
  5. Deterministic Replay and Historical Reconstruction
  6. Disaster Recovery and Trading Continuity
08Testing, Controls and Governance5 chapters
  1. Testing the Trading State Machine
  2. Market Replay, Chaos Testing, and Production Drills
  3. Observability During Trading Hours
  4. Security and Operational Control
  5. Regulatory-Aware System Engineering
09Reference Implementation and Migration4 chapters
  1. Designing the Reference Trading Platform
  2. Implementing the Order-to-Execution Pipeline
  3. Proving Reliability Under Failure
  4. 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.

  1. Restrict external effects

    Disable normal new-order egress and choose a documented safe operating mode while the external truth is uncertain.

  2. Establish authoritative ownership

    Acquire a new gateway epoch and enforce a fence that excludes delayed writers from sending.

  3. Verify the recovery anchor

    Load a consistent snapshot with recorded event cursor, schema/reducer version and integrity digest.

  4. Replay only the justified history

    Use a fixed event corpus, configuration, reference data and virtual clock; keep outbound adapters inert.

  5. Reconstruct effective economics

    Deduplicate executions, retain corrections and rebuild orders, positions and risk reservations.

  6. Reconcile the world outside

    Query venue/broker working orders and executions; resolve or explicitly contain unconfirmed sends.

  7. Apply an accountable release gate

    Require invariant checks and operational sign-off before resuming controlled new-order activity.

  8. 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

Engineering consequence: a green health dashboard is not sufficient evidence that orders, risk, positions and external venue records agree. A release gate has to inspect the business state.

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

Appendix A

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.

Appendix B

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.

Appendix C

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.

Appendix D

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.

Appendix E

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.

Learning scope

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

  1. Foundations (Chapters 1–5): understand what an event proves, distinguish commands from observations, and write acceptance criteria that survive production.
  2. Transport & delivery (6–11): examine ordering, partitions, event contracts, exactly-once scope, durable deduplication and backpressure during stressed markets.
  3. Orders & state (12–18): define lawful transitions, distinguish FIX sessions from business state, and reconstruct fills, corrections and order aggregates.
  4. Risk & accounting (19–24): build pre-trade authorization, manage concurrent reservations, reason about sagas and financial ledgers, and design kill-switch behavior.
  5. Market data & routing (25–30): restore order-book integrity after sequence gaps, model instrument/session context and control execution routing.
  6. Performance & clocks (31–35): measure latency across explicit boundaries, understand queueing and causality, and benchmark without concealing workload assumptions.
  7. Streams & recovery (36–41): handle stale joins and poison messages, fence leaders, reconstruct historical state and recover from a failure domain outage.
  8. Tests & controls (42–46): write state-machine tests, replay market events, inject faults, instrument operations and address security and regulatory scope.
  9. 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

Continue exploring