45 / 60 · Transactions

Stock Exchange — Production Architecture

All designs

Accept orders, match deterministically, publish market data, and preserve an auditable ledger.

5M orders/s · microsecond matching · strict price-time priority
1. High-level architecture and animated call flow

Choose a path, then play or step through exactly how the call moves between components.

← / → step · Space play
CLOUD / MULTI-AZ DEPLOYMENT STOCK EXCHANGE · PRODUCTION TOPOLOGY 15 named components · solid = request/data dependency · warm curve = control, event, or repair path MULTI-ZONE · VERSIONED · REPLAYABLE 01 · REQUEST & CONTROL02 · DOMAIN & COORDINATION03 · DATA, ASYNC & OPERATIONSrequestauthenticateroutevalidateread / reservecommitpublishconsumeprojectobserverepairreconcileinvalidateacknowledgepolicy snapshotevent streamtelemetry 01 EXTERNAL Trading Client interaction boundary 02 EDGE Session Gateway protocol · auth · quota 03 SECURITY Authentication decision & coordination 04 SECURITY Pre-Trade Risk decision & coordination 05 EDGE Symbol Router routing & ownership 06 SERVICE Input Sequencer domain subsystem 07 SERVICE Matching Engine decision & coordination 08 SERVICE Order Book domain subsystem 09 STREAM Execution Journal durable ordered events 10 SERVICE Market DataPublisher domain subsystem 11 SERVICE Drop Copy domain subsystem 12 DATA Clearing Ledger protocol · auth · quota 13 SERVICE Surveillance domain subsystem 14 SERVICE Snapshot/Replay low-latency read path 15 SERVICE Trading HaltControl domain subsystem externaledgeservicedatastreamsecurityops
Step 1 / 8Trading Client

The caller starts the operation at Trading Client with a stable request and retry identity.

  1. 01 · Trading ClientThe caller starts the operation at Trading Client with a stable request and retry identity.
  2. 02 · Session GatewayAuthenticate session, validate command sequence, and run deterministic pre-trade risk.
  3. 03 · Symbol RouterRoute symbol to one sequencer and append command to the replicated journal.
  4. 04 · AuthenticationMatching engine applies price-time priority and emits executions plus book deltas.
  5. 05 · Input SequencerPublish market data and drop-copy asynchronously from the canonical event sequence.
  6. 06 · Matching EngineClearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.
  7. 07 · Clearing LedgerClearing Ledger receives the committed result or event and advances its versioned state.
  8. 08 · Execution JournalExecution Journal durably records side effects so workers can replay them independently.
2. Critical request and recovery sequence
MUTATION / COMMITTrading ClientACTOR 01SessionGatewayACTOR 02Pre-Trade RiskACTOR 03Order BookACTOR 04ONLINE / READ + RECOVERYTrading ClientACTOR 01AuthenticationACTOR 02InputSequencerACTOR 03Trading HaltControlACTOR 04Authenticate session, validate / command sequence, and runRoute symbol to one sequencer and / append command to the replicatedMatching engine applies price-time / priority and emits executions pluscommitted result + eventMatching engine applies price-time / priority and emits executions plusPublish market data and drop-copy / asynchronously from the canonicalClearing/surveillance reconcile / executions; snapshots plus journalcached/read result + cursortimeout → retry same identity → read committed truth → reconcile

Trading Client

  • Owns client protocol, request identity, retry, and resume behavior.
  • Stateless or lease-scoped; durable progress lives elsewhere.

Session Gateway

  • Owns authentication, validation, quotas, deadlines, and routing.
  • Stateless or lease-scoped; durable progress lives elsewhere.

Authentication

  • Owns one bounded domain decision, transition, or operational capability.
  • Partitioned by aggregate/key and guarded by version, uniqueness, or fencing.

Pre-Trade Risk

  • Owns one bounded domain decision, transition, or operational capability.
  • Partitioned by aggregate/key and guarded by version, uniqueness, or fencing.

Complete System Design Tutorial

The design separates the latency-sensitive online path, the correctness-critical durable transition, and asynchronous projection or repair work. Each chapter below explains one decision shown in the diagrams.

1. Requirements and scope

Functional requirements

  • Execute the primary stock exchange workflow and return an observable result.
  • Expose the concrete operations shown below with stable retry identities.
  • Allow operators to inspect, disable, repair, or replay ambiguous state.
  • Keep derived analytics and notifications off the correctness-critical path.

Non-functional requirements

  • Design for 5M orders/s · microsecond matching · strict price-time priority.
  • Protect the named business invariant under concurrency and partial failure.
  • Scale by an explicit aggregate/partition key without one global mutex.
  • Degrade intentionally when cache, queue, store, or regional ownership is unavailable.
Primary invariant: no scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail.
↑ top

2. Capacity assumptions

State assumptions before choosing technology. The supplied workload is 5M orders/s · microsecond matching · strict price-time priority. Convert it into peak throughput, retained records, bandwidth, and failure budget; then connect each number to a component.

DimensionWorking estimateDesign implication
Traffic5M orders/s · microsecond matching · strict price-time prioritySeparate online compute, durable state, and asynchronous consumers.
Peak factor5–10× averageAdmission control, autoscaling headroom, and hot-key protection.
Stored statewrite rate × retention × record bytesPartition count, indexes, compaction, backup, and archival tier.
Networkpeak operations × payload sizeBatching, compression, edge placement, and egress budget.
Availability99.9–99.99%Multi-zone replicas, tested failover, and dependency error budgets.
RecoveryRPO/RTO by invariantAck boundary, replay retention, reconciliation, and operator runbooks.
Do not cargo-cult the numbers: show the arithmetic, name the uncertain variable, and say which production metric will replace the interview estimate.
↑ top

3. API and data model

NEW_ORDER(symbol, side, price, qty, client_order_id)
CANCEL(order_id, expected_version)
GET /v1/books/{symbol}snapshot/cursor
STREAM executions/market-data

Authoritative records and indexes

order(order_id, symbol, side, price, remaining, sequence)

execution(exec_id, maker, taker, price, qty, sequence)

book_snapshot(symbol, sequence, levels, checksum)

risk_limit(account, buying_power, position_limit, version)

Command and event envelopes

# Command envelope
operation: NEW_ORDER(symbol, side, price, qty, client_order_id)
request_id: req_01J...
idempotency_key: idem_7f2...
aggregate_key: stock-exchange_123
expected_version: 17
payload: {...}

# Durable event
event_id: evt_01J...
aggregate_key: stock-exchange_123
event_type: stock_exchange_committed
schema_version: 3
trace_id: tr_8ac...

The authoritative aggregate and idempotency record share a transactional or conditional-write boundary. Event streams, search indexes, caches, analytics, and dashboards are rebuildable projections.

↑ top

4. Why this architecture and what it costs

The boxes are not a shopping list. Each boundary exists because it owns a different invariant, scaling dimension, data lifecycle, security policy, or failure domain. The table makes those choices explicit and shows when the design should remain simpler.

ComponentOwned responsibilityWhy separate itRejected alternativeCost and evolution trigger
Trading ClientOwns client protocol, request identity, retry, and resume behavior. In this design it participates in: Authenticate session, validate command sequence, and run deterministic pre-trade risk.Separates a distinct scale, ownership, policy, or failure boundary. It prevents the external caller from also owning the contract and failure behavior of Session Gateway.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Sequencer fails after accepting order” to the external caller.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Trading Client boundary before extracting or scaling it.
Session GatewayOwns authentication, validation, quotas, deadlines, and routing. In this design it participates in: Route symbol to one sequencer and append command to the replicated journal.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Trading Client from also owning the contract and failure behavior of Authentication.Put protocol, authentication, quotas, and business transitions in one process. Acceptable at low scale, but it couples external traffic risk to domain releases. Here that simpler choice would couple “Duplicate client order ID” to Trading Client.Costs another hop, policy distribution, and a high-blast-radius fleet. Introduce it when many clients or services need one protocol and protection boundary. Measure the latency, saturation, lag, or mismatch at the Session Gateway boundary before extracting or scaling it.
AuthenticationOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Matching engine applies price-time priority and emits executions plus book deltas.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Session Gateway from also owning the contract and failure behavior of Pre-Trade Risk.Embed policy in every caller. Rules then drift by deployment version and emergency changes require fleet-wide redeployment. Here that simpler choice would couple “Market order crosses thin book” to Session Gateway.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Authentication boundary before extracting or scaling it.
Pre-Trade RiskOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Publish market data and drop-copy asynchronously from the canonical event sequence.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Authentication from also owning the contract and failure behavior of Symbol Router.Embed policy in every caller. Rules then drift by deployment version and emergency changes require fleet-wide redeployment. Here that simpler choice would couple “Market data consumer misses gap” to Authentication.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Pre-Trade Risk boundary before extracting or scaling it.
Symbol RouterOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Clearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Pre-Trade Risk from also owning the contract and failure behavior of Input Sequencer.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Trading halt races queued orders” to Pre-Trade Risk.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Symbol Router boundary before extracting or scaling it.
Input SequencerOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Authenticate session, validate command sequence, and run deterministic pre-trade risk.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Symbol Router from also owning the contract and failure behavior of Matching Engine.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Sequencer fails after accepting order” to Symbol Router.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Input Sequencer boundary before extracting or scaling it.
Matching EngineOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Route symbol to one sequencer and append command to the replicated journal.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Input Sequencer from also owning the contract and failure behavior of Order Book.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Duplicate client order ID” to Input Sequencer.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Matching Engine boundary before extracting or scaling it.
Order BookOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Matching engine applies price-time priority and emits executions plus book deltas.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Matching Engine from also owning the contract and failure behavior of Execution Journal.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Market order crosses thin book” to Matching Engine.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Order Book boundary before extracting or scaling it.
Execution JournalPreserves durable ordering, replay, and consumer checkpoints. In this design it participates in: Publish market data and drop-copy asynchronously from the canonical event sequence.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Order Book from also owning the contract and failure behavior of Market Data Publisher.Call every downstream consumer synchronously. That couples user latency and availability to analytics, notification, indexing, and audit dependencies. Here that simpler choice would couple “Market data consumer misses gap” to Order Book.Costs eventual consistency, schema evolution, replay tooling, idempotent consumers, and lag operations. Earn it when bursts or downstream failure must not block acknowledgment. Measure the latency, saturation, lag, or mismatch at the Execution Journal boundary before extracting or scaling it.
Market Data PublisherOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Clearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Execution Journal from also owning the contract and failure behavior of Drop Copy.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Trading halt races queued orders” to Execution Journal.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Market Data Publisher boundary before extracting or scaling it.
Drop CopyOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Authenticate session, validate command sequence, and run deterministic pre-trade risk.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Market Data Publisher from also owning the contract and failure behavior of Clearing Ledger.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Sequencer fails after accepting order” to Market Data Publisher.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Drop Copy boundary before extracting or scaling it.
Clearing LedgerOwns authentication, validation, quotas, deadlines, and routing. In this design it participates in: Route symbol to one sequencer and append command to the replicated journal.Defines the source of truth and commit boundary. It prevents Drop Copy from also owning the contract and failure behavior of Surveillance.Let each service persist its own interpretation. That removes one clear commit boundary and makes retries, support, and reconciliation ambiguous. Here that simpler choice would couple “Duplicate client order ID” to Drop Copy.Costs schema migration, replication, backup, and shard ownership. Split storage only when access patterns, retention, or compliance boundaries materially differ. Measure the latency, saturation, lag, or mismatch at the Clearing Ledger boundary before extracting or scaling it.
SurveillanceOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Matching engine applies price-time priority and emits executions plus book deltas.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Clearing Ledger from also owning the contract and failure behavior of Snapshot / Replay.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Market order crosses thin book” to Clearing Ledger.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Surveillance boundary before extracting or scaling it.
Snapshot / ReplayOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Publish market data and drop-copy asynchronously from the canonical event sequence.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Surveillance from also owning the contract and failure behavior of Trading Halt Control.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Market data consumer misses gap” to Surveillance.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Snapshot / Replay boundary before extracting or scaling it.
Trading Halt ControlOwns one bounded domain decision, transition, or operational capability. In this design it participates in: Clearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.Separates a distinct scale, ownership, policy, or failure boundary. It prevents Snapshot / Replay from also owning the contract and failure behavior of operators and repair tooling.Keep this behavior inside an adjacent service. Prefer that simpler option until independent scale, ownership, policy, or failure isolation is measurable. Here that simpler choice would couple “Trading halt races queued orders” to Snapshot / Replay.Costs an interface, deployment, telemetry, ownership, and failure mode. Keep it in-process first; extract when independent scale or reliability pays for the boundary. Measure the latency, saturation, lag, or mismatch at the Trading Halt Control boundary before extracting or scaling it.
Decision 01

Chosen boundary vs simpler monolith

Route one symbol to one deterministic matching sequencer; parallel writers would require coordination on every price level and compromise price-time priority.

A single deployable with one transactional store is the right starting point for a small stock exchange workload. The proposed boundary becomes justified when route one symbol to one deterministic matching sequencer; parallel writers would require coordination on every price level and compromise price-time priority. Separating it contains the named failure “Sequencer fails after accepting order” without placing unrelated work on the critical path.

Decision 02

Correctness vs availability

Persist an ordered command/event journal before external acknowledgment, then rebuild books by replay instead of synchronously updating many stores.

The design coordinates only where no scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail. Everywhere else it accepts bounded staleness or asynchronous propagation. The alternative—strong coordination for every projection—simplifies the mental model but increases tail latency and turns partitions into broad write unavailability.

Decision 03

Operational cost and evolution

Market-data publication is derived and may lag matching; the execution ledger is authoritative and independently reconciled.

This choice adds dashboards, ownership, schema compatibility, capacity planning, and recovery runbooks. Start with the minimum topology that supports “Matching engine applies price-time priority and emits executions plus book deltas.” and extract another service only when measured throughput, blast radius, data lifecycle, or team ownership changes independently.

Why this design: the synchronous path contains only the decisions required to protect no scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail. Durable projections, notifications, indexing, analytics, and repair are isolated so their load or failure cannot corrupt the acknowledged operation.
Correctness boundary

Route one symbol to one deterministic matching sequencer; parallel writers would require coordination on every price level and compromise price-time priority.

Scale boundary

Persist an ordered command/event journal before external acknowledgment, then rebuild books by replay instead of synchronously updating many stores.

Operational boundary

Market-data publication is derived and may lag matching; the execution ledger is authoritative and independently reconciled.

↑ top

5. Critical flow and algorithm

01

Authenticate session, validate command sequence, and run deterministic pre-trade risk.

02

Route symbol to one sequencer and append command to the replicated journal.

03

Matching engine applies price-time priority and emits executions plus book deltas.

04

Publish market data and drop-copy asynchronously from the canonical event sequence.

05

Clearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.

Retry-safe mutation skeleton

identity = authenticate(request)
prior = idempotency.get(identity, request.key)
if prior: return prior.result

current = authoritative_store.read(partition_key)
next_state, events = domain.transition(current, request)
authoritative_store.compare_and_set(current.version, next_state)
idempotency.commit(request.key, next_state.result)
outbox.append(events)
return next_state.result
Exactly-once business effect: the network can duplicate requests. Stable identities, conditional state transitions, immutable event IDs, and reconciliation make the user-visible effect happen once.
↑ top

6. Caching, hot keys, and backpressure

Cache policy

Add a cache only for a measured repeated read; do not place mutable correctness state in a disposable layer.

Hot partition or tenant

Measure per-key and per-tenant skew. Replicate safe reads, isolate the offender, salt only when ordering permits, and enforce budgets.

Backpressure

Bound queues, buffers, connection pools, and concurrency. Shed low-priority work and scale from lag/oldest-item age rather than CPU alone.

Stampede and retry storms

Use single-flight/coalescing, jittered expiry, bounded retries, exponential backoff, and circuit breakers so one dependency failure does not multiply traffic.

Cache outage rule: never allow every miss to fall through simultaneously. Use local protection, request coalescing, circuit breakers, bounded pools, and controlled fallback.
↑ top

7. Partitioning and consistency

partition = stable_hash(primary_or_aggregate_key) → shard owner
write = conditional_update(expected_version)
read_projection = versioned and rebuildable

Strong boundary

no scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail. Use a uniqueness constraint, serializable/conditional write, expected version, or fencing token at this boundary.

Eventual boundary

Analytics, notifications, search, read models, and operational dashboards may lag when freshness is observable and replay exists.

OperationConsistencyReason
Authoritative mutationConditional / serializableProtect uniqueness, ownership, money, inventory, order, or legal state transition.
Read after own writePrimary, session token, or cache warmThe caller must observe the result it just committed.
Ordinary read projectionBounded stale where safeReplicas and caches improve latency when version/freshness is visible.
Analytics and operationsEventual + replayFreshness is less important than isolating the online path.
  • Route every mutation for one aggregate to one owner/partition epoch.
  • Use cursors rather than offsets for changing ordered collections.
  • Retain tombstones until replication and repair windows close.
  • Move shard ownership through versioned maps and dual-read verification.
↑ top

8. Failure drills and recovery

FailureRuntime behaviorRecovery proof
Sequencer fails after accepting orderStop unsafe progress, serve only explicitly safe degraded behavior, and recover from durable state.Reconciliation returns zero invariant gaps; lag/replica health and user-visible SLO return to baseline.
Duplicate client order IDResolve at source of truth with uniqueness, expected version, lease generation, or monotonic cursor.Reconciliation returns zero invariant gaps; lag/replica health and user-visible SLO return to baseline.
Market order crosses thin bookStop unsafe progress, serve only explicitly safe degraded behavior, and recover from durable state.Reconciliation returns zero invariant gaps; lag/replica health and user-visible SLO return to baseline.
Market data consumer misses gapStop unsafe progress, serve only explicitly safe degraded behavior, and recover from durable state.Reconciliation returns zero invariant gaps; lag/replica health and user-visible SLO return to baseline.
Trading halt races queued ordersResolve at source of truth with uniqueness, expected version, lease generation, or monotonic cursor.Reconciliation returns zero invariant gaps; lag/replica health and user-visible SLO return to baseline.

Recovery checkpoint

# Recovery checkpoint
scenario: Sequencer fails after accepting order
operation_id: op_01J...
aggregate_key: stock-exchange_123
last_durable_version: 18
projection_checkpoint: partition-07@offset-482901
retry_policy: same_identity / bounded_backoff
reconciliation_status: pending
owner: Trading Halt Control

Every dependency needs a timeout, retry budget, circuit policy, and explicit fail-open, fail-closed, stale, or read-only mode. “Highly available” is incomplete until degraded behavior is named.

↑ top

9. Security, regions, and observability

Security and abuse

  • Authenticate at ingress and authorize the exact resource/tenant on every operation.
  • Encrypt transport and durable data; tokenize or isolate sensitive material.
  • Rate-limit by tenant, actor, resource, and network; detect enumeration and anomalous fan-out.
  • Redact secrets and personal data before logs or analytical storage.
  • Audit privileged mutations, support access, policy changes, and forced recovery.

Signals that prove correctness

  • User-visible success rate and p50/p95/p99 latency.
  • Timeouts, circuit state, saturation, and replica health by dependency.
  • Queue lag, oldest-item age, retries, and dead-letter growth.
  • Conflict, duplicate-suppression, and reconciliation mismatch counts.
  • Business drill: Sequencer fails after accepting order — alert before the user-visible invariant is violated.

Regional evolution

  1. Begin multi-zone with tested failover, backups, and reconciliation.
  2. Add global stateless ingress and regional read projections.
  3. Keep one write owner per aggregate or partition where coordination is expensive.
  4. Move ownership with epochs/fencing; avoid silent simultaneous writers.
  5. Use expand/contract schemas, canaries, shadow reads, and reversible cutovers.
↑ top

10. Interviewer follow-ups

How does price-time priority work?

Route one symbol to one deterministic matching sequencer; parallel writers would require coordination on every price level and compromise price-time priority. Walk the concrete lifecycle step “Authenticate session, validate command sequence, and run deterministic pre-trade risk.” Then test it against “Sequencer fails after accepting order”. State the retry identity, durable checkpoint, recovery signal, and cost of the alternative.

How do you recover a matching engine?

Persist an ordered command/event journal before external acknowledgment, then rebuild books by replay instead of synchronously updating many stores. Walk the concrete lifecycle step “Route symbol to one sequencer and append command to the replicated journal.” Then test it against “Duplicate client order ID”. State the retry identity, durable checkpoint, recovery signal, and cost of the alternative.

How are market orders protected?

Market-data publication is derived and may lag matching; the execution ledger is authoritative and independently reconciled. Walk the concrete lifecycle step “Matching engine applies price-time priority and emits executions plus book deltas.” Then test it against “Market order crosses thin book”. State the retry identity, durable checkpoint, recovery signal, and cost of the alternative.

How is market data fanned out?

Route one symbol to one deterministic matching sequencer; parallel writers would require coordination on every price level and compromise price-time priority. Walk the concrete lifecycle step “Publish market data and drop-copy asynchronously from the canonical event sequence.” Then test it against “Market data consumer misses gap”. State the retry identity, durable checkpoint, recovery signal, and cost of the alternative.

How do trading halts work?

Persist an ordered command/event journal before external acknowledgment, then rebuild books by replay instead of synchronously updating many stores. Walk the concrete lifecycle step “Clearing/surveillance reconcile executions; snapshots plus journal replay recover the engine.” Then test it against “Trading halt races queued orders”. State the retry identity, durable checkpoint, recovery signal, and cost of the alternative.

Answer pattern: state the invariant, choose a mechanism, walk one failure, name the recovery signal, and explain the cost of the alternative.
↑ top

11. How to present this in 45 minutes

TimeWhat to cover
0–5 minClarify scope, workload, SLOs, and the correctness invariant.
5–10 minEstimate throughput/storage and define concrete APIs and records.
10–20 minDraw online, durable-write, and asynchronous/repair paths.
20–30 minExplain the exact lifecycle, partition key, and concurrency control.
30–38 minDiscuss caching, hot keys, replication, and backpressure.
38–43 minRun failure drills, security, observability, and regional evolution.
43–45 minSummarize the five most important choices and trade-offs.

Final decision summary

Invariantno scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail.
PartitioningStable aggregate/key hash with versioned ownership and measured hot-key isolation.
CommitExpected version or uniqueness at the authoritative state boundary.
Async workDurable outbox/log, idempotent consumers, checkpoints, and replay.
RecoverySame operation identity, durable truth lookup, and business reconciliation.

Closing summary

CLOSING “The design protects no scarce resource or monetary effect is created twice, lost after acknowledgment, or committed without an audit trail. The online path stays bounded, authoritative state is versioned and partitioned, and asynchronous work is replayable and observable.”
↑ top