Introduction

matching-engine processes spot orders with price-time priority. The Rust workspace separates core types, matching, shard orchestration, persistence and network delivery. TCP and Unix domain socket clients use binary protocol v2.

Supported orders include limit, market, stop-limit, stop-market, trailing-stop and iceberg. Time-in-force choices are GTC, IOC, FOK and GTD. Legacy sessions own their orders and support configurable per-symbol risk limits. Financial mode uses funded accounts, mandatory account self-trade prevention and an authenticated gateway.

Start with the quick start. Integrators should read the protocol and recovery contract before implementing reconnects.

The financial pilot adds PostgreSQL balances, reservations, quote fees and settlement through an internal mTLS API. It requires a new ledger and an empty financial book. Manual funding records accounting entries without transferring real assets. The legacy session API remains available separately.

There is no replication, consensus or automatic failover. Journals and durable request history grow with activity. Network latency depends on storage sync, TLS, workload and hardware; benchmark the complete path before setting an SLA.

Quick start

Install Rust 1.96 or newer. Clone the repository and build the TLS-capable server:

git clone https://github.com/rekurt/matching-engine.git
cd matching-engine
cargo build --release --locked -p me-server --features tls
./target/release/me-server --config config.toml

The sample config defines BTC/USDT, ETH/USDT and SOL/USDT. Trading listens on 127.0.0.1:9090, HTTP on 127.0.0.1:9091, and the WAL directory is ./data/wal. TLS is available in the binary but is enabled only when certificate paths are configured.

In a second terminal, check readiness and run the Go example:

curl --fail http://127.0.0.1:9091/ready
cd examples/go
go run . 127.0.0.1:9090

The example places crossing limit orders, reads their execution events and cancels a resting order. Run it against a fresh test data directory: previously used order IDs remain part of durable history.

Stop the server with SIGINT or SIGTERM. On restart, use the same symbol/risk configuration, shard topology and whole data directory. See deployment before changing recovery settings or exposing listeners remotely.

For a temporary in-memory experiment, set [wal] enabled = false in a separate config. That disables crash recovery and is not a durable deployment.

Configuration

Pass --config config.toml. Without it, the binary uses built-in defaults. CLI overrides are --tcp-addr, --metrics-addr, --shards and --uds-path. Unknown TOML fields and invalid combinations are rejected before trading starts.

Server

FieldDefaultMeaning
server.tcp_addr127.0.0.1:9090Trading listener
server.metrics_addr127.0.0.1:9091HTTP health, metrics and admin
server.shards0Auto CPU count; pin a count for recovery compatibility
server.uds_pathabsentOptional Unix domain socket
server.allow_plaintext_remotefalseExplicit opt-in for non-loopback plaintext TCP
server.clockcoarsesystem, coarse or rdtsc
server.pin_threadsfalseLinux CPU affinity
server.shutdown.drain_timeout_secs30Connection drain deadline
server.heartbeat.interval_ms5000Advertised heartbeat interval
server.heartbeat.timeout_ms15000Connection read timeout
server.session.replay_buffer_size1000Per-session replay frame capacity
server.session.ttl_secs60Idle lifetime for unused sessions

Configure server.tls.cert_path and key_path together; client_ca_path enables required client certificates. TLS needs the tls build feature. The HTTP listener has no native TLS.

server.admin.api_key is empty by default, disabling halt/resume routes. Configured keys require at least 16 printable, non-space ASCII characters. Status and metrics remain public; protect the HTTP listener with a private network or proxy.

Symbols and risk

Each [[symbols]] entry defines an ID, base/quote names, price/quantity scales and decimal-string limits. See trading pairs. The optional [symbols.risk] table enables these controls:

FieldMeaning
max_order_qtyMaximum order quantity, including hidden quantity
max_order_notionalConservative quote notional cap
price_band_bpsDeviation from reference price; zero disables
reference_priceInitial reference price as a decimal string
max_orders_per_secondToken-bucket limit; zero disables
max_open_ordersResting-order limit; zero disables
trading_enabledAdmission switch
self_trade_preventionReject same-session self-matches

Without a risk table, these checks do not run. Market orders subject to notional/reference checks fail closed if no reference price is available. Seed reference_price or establish a traded reference. Position limits are not supported without an external account ledger.

invariant_policy is halt_symbol by default. strict panics on internal invariant violations; continue logs and continues and should be reserved for controlled recovery.

Storage

FieldDefaultMeaning
wal.enabledtrueEnable durable recovery
wal.modeprepre or post; both persist decisions/outcomes before reply
wal.path./data/walJournal directory
wal.sync_interval100Legacy writer interval; the server syncs each decision explicitly, so this does not batch server replies
wal.snapshot_dirderivedDefaults to {wal.path}/snapshots
wal.snapshot_interval100000Commands per shard checkpoint; zero disables

Snapshot creation does not truncate decision history. Symbol/risk settings and shard topology are part of the recovery contract. See deployment and recovery for backups and upgrades.

Trading pairs

Each [[symbols]] entry registers one symbol. IDs must be unique. Prices and quantities on the wire always use scale 10^8; price_scale and qty_scale do not change the wire scale.

[[symbols]]
id = 0
base = "BTC"
quote = "USDT"
price_scale = 2
qty_scale = 8
min_qty = "0.00001"
max_qty = "10000.0"
qty_step = "0.00001"
price_step = "0.01"
invariant_policy = "halt_symbol"

[symbols.risk]
max_order_qty = "10000.0"
max_order_notional = "100000000.0"
price_band_bps = 1000
reference_price = "50000.0"
max_orders_per_second = 1000
max_open_orders = 100000
trading_enabled = true
self_trade_prevention = false

Limits and steps are decimal strings, parsed without binary floating-point rounding. Quantity must be positive, within min/max bounds and a multiple of qty_step. Limit prices must be positive and a multiple of price_step.

For example, 50000.50 is raw price 5000050000000 and 0.5 is raw quantity 50000000, regardless of symbol display scales. Use checked integer/decimal conversion in clients.

Adding or changing symbols, risk settings or shard count in an existing durable deployment can make recovery incompatible. Validate against copied storage and follow the upgrade procedure.

Financial pilot

The v0.2.0-rc.1 candidate adds a funded mode alongside the legacy session API. See the validation report for checks, measured workload and limits. Start with a new PostgreSQL ledger and an empty financial data directory. This mode does not connect to banks, blockchains or real assets, and does not provide automatic failover.

Authority and limits

PostgreSQL owns balances, reservations, immutable postings and settlement cursors. The matcher journal owns execution decisions. One gateway owns the database lease and the matcher connection. Financial mode serializes all configured symbols in shard 0; legacy sharding is unchanged.

Every decision is applied as one database transaction, including both counterparties, maker/taker fees, order states and cursor. A duplicate decision has no financial effect. Unknown orders, rejected versions, identity mismatches and broken journal lineage require reconciliation. A timeout or disconnect never releases a reservation.

Amounts are signed integers at scale 10^20, stored in PostgreSQL NUMERIC(78,0). HTTP monetary values are decimal strings. Instruments retain the engine's eight-decimal price and quantity units. Funding and withdrawals default to eight fractional places; an asset can explicitly select another precision, up to twenty. Smaller settlement dust remains available in the account.

Fees are nonnegative integer basis points, charged in the quote asset, without rebates. Each order retains its fee schedule. A buy reserves price × full remaining quantity plus the larger maker/taker fee. A sell reserves the full base quantity and pays its fee from quote proceeds. Iceberg hidden quantity and inactive stops are fully funded. Market, stop-market and trailing stop-market orders require a positive execution ceiling for buys or floor for sells; an unfilled remainder is cancelled.

Amend reserves the largest possible combined cost of old-version fills followed by new-version fills. For example, changing 10 × 200 to 20 × 150 can require 3500, before fees. An old-version fill cannot release the coverage still needed by a pending amendment. Stop and iceberg amend restrictions remain enforced by the engine.

Internal HTTP API

Build me-server with --features financial and build me-gateway. The server's --financial-config PATH selects the isolated financial listener; it does not open legacy TCP or UDS order listeners. The gateway uses --config PATH and reads PostgreSQL credentials from ME_LEDGER_DATABASE_URL, or the configured environment variable name.

Both financial connections require TLS 1.3 and client certificates. Configuration binds the SHA-256 fingerprint of each leaf certificate to a service identity. The gateway's principals map grants explicit read, trade, funding and admin permissions, plus an accounts allowlist or explicit all_accounts: true. An admin permission does not implicitly grant trading or funding.

MethodRoutePermissionResult
GET/health/liveKnown certificateProcess is running
GET/health/readyreadDatabase, lease, recovery and settlement admission state
GET/metricsreadPrometheus gateway metrics
POST/v1/admin/accountsadminStable account UUID for { "key": "...", "name": "..." }
POST/v1/admin/maintenanceadmin{ "enabled": true/false }; returns a durable matcher watermark
POST/v1/admin/reconcileadminVerify accounting and matching cursor while the engine is paused
GET/v1/accounts/{account}/balancesread + accountAvailable and reserved decimal strings by asset
POST/v1/accounts/{account}/orderstrade + accountDurable placement receipt, HTTP 202
GET/v1/accounts/{account}/orders/{id}read + accountCurrent order state
POST/v1/accounts/{account}/orders/{id}/canceltrade + account{ "key": "..." }; saved request UUID, HTTP 202
POST/v1/accounts/{account}/orders/{id}/amendtrade + accountKey and optional decimal price / quantity, HTTP 202
GET/v1/accounts/{account}/requests/{key}read + accountCurrent intent status
GET/v1/accounts/{account}/eventsread + accountAccount-filtered decision pages
POST/v1/accounts/{account}/fundingfunding + accountBalanced external-input journal
POST/v1/accounts/{account}/withdrawalsfunding + accountBalanced external-output journal; no external transfer
POST/v1/accounts/{account}/batch/placetrade + accountArray of 1–20 placement requests, per-item receipts/errors
POST/v1/accounts/{account}/batch/canceltrade + accountArray of 1–50 { "key": "...", "order_id": 1 } requests

A placement request is:

{
  "key": "client-intent-001",
  "order": {
    "symbol": 0,
    "side": "buy",
    "order_type": "limit",
    "time_in_force": "GTC",
    "price": "100.00",
    "quantity": "1.00000000"
  }
}

Order types are limit, market, stop_limit, stop_market. TIF is GTC, IOC, FOK or GTD. Optional fields are protection_price, stop_price, trail_offset, display_quantity, Unix-nanosecond expire_at, and flags containing post_only or maker_or_cancel. Engine validation still determines legal combinations. An expired GTD is durably rejected before matching.

Funding and withdrawal bodies contain asset, decimal-string amount, and a globally unique external_reference. Reusing a reference for a different transfer is a conflict. The operation records accounting only.

HTTP 202 confirms a saved intent and funded outbox entry; it does not promise execution or final acceptance. Query the request and order after a timeout. Repeat the same key and validated intent, rather than create a new key. A different intent under the same key returns 409. Placement retries return the original receipt even after the order changes; current state has its own endpoint. Batch items are independent; no atomicity across symbols is promised.

Event queries accept after (decision sequence), digest (the preceding decision hash), and limit (1–256, default 32). Begin at sequence zero and a digest of 64 zeroes. A page contains account-specific events grouped by decision and the next cursor. Commit all events in a decision with the cursor in one application transaction. Re-reading a page is allowed; never infer settlement from an open-order snapshot.

Financial wire and storage

The existing v2 payloads remain unchanged. Financial mode requires a v2 handshake payload containing version byte 2 and the capabilities TLV: tag 1 (u16 LE), length 8 (u16 LE), value u64 LE. Required bits are TLS (5), financial commands (8), durable decisions (9), protected markets (10) and maintenance barrier (11). A peer missing a required bit is rejected.

New messages retain the 22-byte v2 header. JSON payloads use the internal funded contracts from me-financial; raw prices and quantities there use 10^8 units.

TypeMeaning
0x30Funded place/cancel/amend with immutable request, account, order, reserve, fee and version identities
0x31Decision page query: after, digest, limit
0x32Engine identity, instrument fingerprint, capabilities and watermarks
0x33Persist a maintenance barrier or resume
0x38Correlated reply: result or error

Mutation frame sequence and request ID are the persisted outbox wire request ID. Control queries use sequence zero and a nonzero correlation ID; replies use sequence zero. Financial replay comes from the durable feed, independently of legacy session replay. The gateway persists the complete encoded mutation before sending it and retransmits those bytes unchanged.

The matcher publishes an active directory only after its manifest and empty journal are durable. Incomplete .initializing-* directories were never visible to clients. A published generation missing either file fails closed. active/financial.json binds storage version, engine UUID and instrument fingerprint. active/financial.wal starts with MEFIN001; each record carries length, body CRC, WAL sequence, header CRC and JSON decision/replay data. Only an incomplete final write is truncated. Complete corrupt records or replay divergence stop recovery.

Event identity is (engine UUID, shard, WAL sequence, event index). Account event indices enumerate command outcomes, fills, then order outcomes. A fill appears once in a financial decision, even though both counterparties receive notifications. Order bindings let the ledger check the account, reservation and frozen fee version before posting funds.

The financial database has an explicit schema version. SQLx migration checksums and version checks reject incompatible binaries or modified migrations. Legacy WAL and snapshots retain their existing format. Financial mode starts with fresh storage; it does not import a legacy book.

Reproducible checks

PostgreSQL integration tests run separately from ordinary workspace tests:

LEDGER_TEST_DATABASE_URL=postgresql://... cargo test -p me-ledger --test postgres -- --ignored
cargo build -p me-server --features financial -p me-gateway
LEDGER_TEST_DATABASE_URL=postgresql://... python3 scripts/financial-smoke.py

The smoke creates a private schema and test CA. It verifies a blocked, unsubmitted outbox before killing the gateway, matcher maintenance recovery, a hard matcher restart, both trading balances, fees, original receipt replay and separate funding permissions. Test credentials and state are written outside the repository when --output points there.

financial-soak.py accepts --seconds (default 3600), --bin-dir, and --output. Its report describes the complete HTTP/reservation/matcher/settlement workload, machine, throughput, percentiles, journal growth and midpoint restart time. Polling and client TLS overhead are part of those measurements. They are not an engine-only latency figure or an SLA.

Local operational rehearsal

The Compose deployment binds only the internal HTTPS API and monitoring consoles to loopback. The matcher and PostgreSQL have no published ports. Its generated CA and certificates are disposable and expire in two days. Production identities, account allowlists, funding privileges and alert recipients require explicit configuration.

python3 scripts/financial-configure.py --output .pilot
docker compose --env-file .pilot/compose.env -f ops/financial/compose.yml up --build -d
curl --cacert .pilot/ca.pem --cert .pilot/admin.pem --key .pilot/admin.key \
  https://localhost:9443/health/ready

The generator refuses to replace an existing directory. Keep .pilot outside Git; it contains private keys, database credentials, the engine journal and configuration. Never regenerate identities over an existing ledger. The example trader has access to all pilot accounts; replace this with explicit account UUIDs before a shared pilot. The read-only monitoring identity cannot trade, fund or administer accounts.

Create a pilot account with the administrator identity:

curl --fail --cacert .pilot/ca.pem --cert .pilot/admin.pem --key .pilot/admin.key \
  -H 'Content-Type: application/json' -d '{"key":"pilot-account-001","name":"Pilot account"}' \
  https://localhost:9443/v1/admin/accounts

Save the returned UUID as ACCOUNT_ID. Provisioning keys are scoped by the administrator certificate's SHA-256 fingerprint. Retain the UUID mapping across certificate rotation; repeating provisioning under a new certificate creates a different namespace.

The generated local administrator also has an explicit funding permission. Use that permission to record initial test funds with a unique external reference:

curl --fail --cacert .pilot/ca.pem --cert .pilot/admin.pem --key .pilot/admin.key \
  -H 'Content-Type: application/json' \
  -d '{"asset":"USDT","amount":"1000","external_reference":"pilot-funding-001"}' \
  "https://localhost:9443/v1/accounts/$ACCOUNT_ID/funding"
curl --fail --cacert .pilot/ca.pem --cert .pilot/admin.pem --key .pilot/admin.key \
  "https://localhost:9443/v1/accounts/$ACCOUNT_ID/balances"

Retry an uncertain funding request with the same external reference and payload. Using a new reference records another accounting input. Withdrawals use the same privilege and precision checks through /withdrawals; neither operation transfers assets outside the ledger. Grant funding separately from trading in a shared pilot.

Readiness requires the PostgreSQL lease, valid engine identity and capabilities, completed recovery, no reconciliation latch, no maintenance barrier, settlement catch-up and sufficient journal disk reserve. A missing database pauses admission; a lost gateway lease requires a restart. Existing reservations remain locked.

Prometheus runs on http://localhost:9091, Alertmanager on http://localhost:9093. The provided receiver logs test deliveries inside the Compose network. Send a test:

curl --fail -H 'Content-Type: application/json' \
  -d '[{"labels":{"alertname":"PilotDeliveryTest","severity":"warning"},"annotations":{"summary":"Local delivery rehearsal"}}]' \
  http://localhost:9093/api/v2/alerts
docker compose --env-file .pilot/compose.env -f ops/financial/compose.yml logs alert-receiver

Replace the local receiver in a deployment-specific Alertmanager configuration to route production notifications. Do not commit recipient credentials. Rules cover admission, unavailable metrics, reconciliation, settlement backlog, stuck intentions and journal disk reserve. Metrics include reserved amounts by currency, worker errors, journal bytes and free space. Monitor PostgreSQL volume space separately on its host. There is no automatic failover or online journal compaction.

Maintenance, backup and restore

  1. Stop client submission. POST {"enabled":true} to /v1/admin/maintenance using the administrator certificate. Gateway admission stops first; reserved intentions drain, then the matcher persists a barrier that also freezes GTD.

  2. GET /v1/admin/checkpoint. It requires matching engine/ledger watermarks, empty outbox, no pending intentions and a successful accounting audit. A timeout or a failed checkpoint leaves admission paused; investigate rather than releasing funds or deleting requests.

  3. Run the backup utility. It checks the checkpoint before and after copying:

    python3 scripts/financial-backup.py --config-dir .pilot --output /secure/pilot-backup
    

    The archive contains a PostgreSQL custom dump, complete engine journal, maintenance snapshot, configuration and private identities. Store it with access restricted to its operator. The manifest records checksums and the agreed watermark. Admission remains paused after backup.

  4. For shutdown, stop the gateway before the matcher. Compose uses SIGINT and a 45-second grace period. An emergency SIGKILL requires journal replay on restart.

  5. Restore only into a new empty database and a new directory. Set ME_RESTORE_DATABASE_URL through a private environment, then run:

    python3 scripts/financial-restore.py --archive /secure/pilot-backup --output /secure/restored-pilot
    

    The utility verifies checksums and refuses an existing destination or nonempty database. Update the restored Compose paths and database connection to the new resources; do not reuse the old volume. Start matcher, then gateway. Confirm the checkpoint matches the backup manifest and balances. POST /v1/admin/reconcile if required, then explicitly resume with {"enabled":false}.

  6. Upgrade only while paused, after a tested backup. Re-run instrument/identity, accounting, cursor and compatibility checks before resuming. Financial schema version mismatches and migration checksum changes stop startup. There is no automatic downgrade path; test a new deployment before cutover.

Never restore an old backup over newer confirmed executions. Preserve both sources and reconcile their complete durable decision histories before planning recovery. A stop caused by corruption, unknown orders or source rollback requires operator investigation; GetOpenOrders and a cleared timeout are insufficient evidence. Financial snapshots retain ownership, reservations, fee versions, price protection, order versions and book state. They are verified against full journal replay; this RC implementation does not truncate the journal or accelerate replay from snapshots.

Fees may be changed only while the ledger is in maintenance, using a new schedule UUID in the gateway configuration. Existing orders retain their original schedule. A schedule UUID can never be reused with different rates.

Expiry processing uses durable batches of at most 128 heap entries per instrument. Before a new command matches, all due expiries are committed in bounded decisions. This prevents a simultaneous GTD sweep across many instruments from exceeding a journal record. A restart between expiry batches continues from the recorded cursor.

The backup utility verifies the snapshot's internal checksum and compares the complete engine snapshot with ledger orders: account ownership, order/fee/reservation versions, hidden remaining quantities and exact reserve requirements. This check supplements the balanced-postings audit. A discrepancy stops backup and leaves admission paused.

Additional rehearsals, with outputs outside the checkout:

LEDGER_TEST_DATABASE_URL=postgresql://... python3 scripts/financial-matrix.py --output /tmp/pilot-matrix
LEDGER_TEST_DATABASE_URL=postgresql://... python3 scripts/financial-faults.py --output /tmp/pilot-faults
LEDGER_TEST_DATABASE_URL=postgresql://... python3 scripts/financial-disk-smoke.py --output /tmp/pilot-disk
python3 scripts/financial-compose-smoke.py --output /tmp/pilot-operations

The disk rehearsal fills an isolated 8 MiB tmpfs volume, leaving the host filesystem untouched. It needs Docker and the locally built matching-engine:financial-pilot image. The Compose rehearsal uses local port 9443 and monitoring ports 9091/9093; stop another local pilot before running it. Its database volumes and private files are retained after shutdown for inspection.

Client integration

This page describes the legacy session protocol. Use the internal financial gateway for funded account operations; its durable decision feed and PostgreSQL cursor provide settlement recovery independently of session replay.

Connect through TCP or UDS, then send Handshake or ResumeSession before order commands. The wire specification defines framing, payloads and sequence numbers.

Keep one ordered reader per connection. Correlate solicited events by request_id; passive fills and stop events use request ID zero. A command can produce several events. An order snapshot ends at OpenOrdersEnd, not at a period of socket silence. Handle fragmented reads and multiple frames in one read. Preserve passive events that arrive before or during a snapshot; commit the snapshot cursor only after validating Begin, End and the declared count.

Persist the session ID and the last applied sequence from the replay stream, as defined in the protocol. Positive-sequence control frames also belong to replay; process and acknowledge them in order. Sequence-zero frames, including SessionResumed, never advance the cursor. Resume with the saved cursor, ignore duplicate replayed events, acknowledge only applied replay frames and retain the original request ID/payload when retrying a mutation. Session IDs are bearer credentials; use TLS and account authorization at the gateway.

If ReplayGap occurs, request GetOpenOrders and validate the complete Begin/Order/End response. That restores open orders, not missed settlement history; reconcile executions against an authoritative ledger before resuming financial processing. Batches are not atomic across symbols.

Supplied clients

ClientUse
Go SDKExisting TCP/UDS client and a separate recovering client with durable checkpoints
Python exampleStandard-library protocol demonstration
TypeScript exampleNode.js Buffer framing and event parsing
Rust exampleTokio framing and basic order flow

Examples live under examples/ in the repository. They demonstrate framing and order flow. For durable session recovery, the Go SDK's separate RecoveringClient persists session identity, receive cursors and original pending mutation bytes. Its application callback must durably apply an event before acknowledgement; ReplayGap requires reconciliation. See the Go guide for storage and delivery guarantees.

See deployment for ownership, durable retries, admission limits and storage requirements.

Go client

The SDK is in clients/go/meclient; the runnable example is in examples/go.

cd examples/go
go run . 127.0.0.1:9090

Dial and DialUDS perform Handshake automatically. For TLS, establish a tls.Conn, pass it to NewClientFromConn and call Handshake before commands.

Use decimal strings for exact prices and quantities (NewDecimalFromString). Avoid floating-point conversion for financial input. ReadEvent returns individual events; ReadEvents provides streaming delivery.

The SDK serializes socket reads and writes, but Ping and Handshake consume their own replies. Do not run them concurrently with the event reader. Use one reading mode per connection.

The original Client supports basic submission/event operations for protocol v2. RecoveringClient adds durable session state, ResumeSession, application checkpoints and retries with original IDs and bytes. Financial settlement still requires the recovery contract and an authoritative execution source.

Recovering client

The existing Client remains available. RecoveringClient adds durable session identity, request/client counters, application cursor and pending mutation bytes. Provide a SessionStore, a context-aware dialer, a stable endpoint identifier, and an ApplySession callback. Run the client in one goroutine and submit mutations from another.

OpenFileSessionStore(path) provides atomic rename + fsync checkpoints with mode 0600 and an exclusive process lock on Linux, macOS and supported BSDs. Other platforms must supply an appropriate store. Corrupt, missing existing or incompatible state fails closed. Never delete the state file to work around a failed resume.

store, err := meclient.OpenFileSessionStore("./private/session.json")
if err != nil { return err }
defer store.Close()
client, err := meclient.NewRecoveringClient(meclient.RecoveryOptions{
    Endpoint: "matching-service-tls-identity",
    Store: store,
    Dial: dialAuthenticatedConnection,
    Apply: applyToCheckpoint,
})
if err != nil { return err }
go func() { errors <- client.Run(ctx) }()
requestID, err := client.PlaceOrder(ctx, order)

The dialer is responsible for authenticating TLS and must not change service identity behind the same endpoint label. The application callback receives positive-sequence control frames as well as command replies and passive events. It returns the application's JSON checkpoint. The file store saves that checkpoint with the cursor before the SDK sends an ACK. A database store must commit application changes and the session checkpoint in the same transaction. Use an outbox for external side effects. Do not synchronously call this client from its application callback.

Delivery is at least once across a crash before application commit. Correlate command replies by RecoveryFrame.RequestID; passive events use zero. Commands are removed from pending state only after an applied Pong barrier confirms preceding command processing. On reconnect the client performs ResumeSession, applies replay and retransmits pending frames with their original IDs and bytes. A submission timeout does not cancel an order; inspect the durable pending list before submitting a new command.

ReplayGap persists ReconciliationRequired and stops recovery. It never starts a new session silently or treats GetOpenOrders as recovery of lost trades. Reconcile executions and application state before explicitly replacing or repairing a checkpoint. The recovering client speaks the legacy session API; the funded gateway has its own persisted outbox and financial decision feed.

The bundled file store uses Unix advisory locks (Linux, macOS and supported BSDs). On other platforms, provide a durable SessionStore with equivalent exclusive ownership and atomic checkpoint guarantees. Do not remove or replace a live lock file; detected replacement stops the store until reconciliation.

Python example

examples/python/client.py demonstrates TCP framing with Python's standard library (socket, struct and decimal conversion). It requires Python 3.10 or newer.

python3 examples/python/client.py 127.0.0.1 9090

The example performs Handshake, submits orders on symbol 1 and reads events. It is intended for a fresh local test server. Its optional arguments are host and port; adapt its symbol and order values before using it with a different configuration.

Run its protocol tests with python3 -m unittest discover -s examples/python. The separate scripts/runtime_smoke.py test client exercises actual TCP/mTLS processes, crash recovery and session resume.

For production integration, implement persistent receive cursors, mutation retries and settlement reconciliation as described in client integration.

Wire protocol v2

TCP and Unix domain sockets carry the same frames. TLS changes the transport, not the frame layout. All integers are little-endian. Prices use signed i64 and quantities use unsigned u64, both scaled by 10^8. Timestamps and expiry times use Unix nanoseconds.

Frame header

OffsetSizeField
04Payload length, excluding the header (u32)
41Version: 2
51Message type
68Sequence (u64)
148Request ID (u64)
22variablePayload

Read exactly the 22-byte header, then the declared payload. One socket read may contain part of a frame or several frames. Regular inbound payloads are limited to 1024 bytes; batch payloads to 4096 bytes.

Client sequences increase strictly within a connection. Sequence zero is accepted only for its first Handshake. Commands and queries require a nonzero request ID; Ping, Handshake, ResumeSession and Acknowledge do not. Reuse the original request ID and exact payload when retrying a mutation.

Positive server sequences identify the per-session replay stream. Replies passed through the active-session response path, including HandshakeAck, Pong, ReplayGap from ResumeSession and some Error frames, are assigned server sequences and journaled when WAL is enabled. A gap detected during pending delivery instead emits ReplayGap directly with sequence zero, outside the replay journal. Replayed frames retain their original sequence. The server rewrites these headers; a Pong header is not the echoed client sequence (its payload reports the last processed client sequence).

Sequence zero is out-of-band and never advances the receive cursor. SessionResumed is sent with zero before the replay frames; errors sent outside the active-session replay path also use zero. Process every positive-sequence frame in order, including control frames, and advance the cursor only after applying it. Solicited order events mirror the request ID; passive owner events use zero.

Connection and recovery

Start with Handshake to create a session, or ResumeSession to recover one. Do not send order commands before acceptance. Persist the session ID and last applied positive server sequence outside the connection. A session can have only one active connection.

TypeNamePayload, in field order
0x04PingEmpty, or last applied server sequence (u64) as cumulative ACK
0x05HandshakeEmpty, or client version (u8, use 2)
0x06ResumeSessionSession ID (16 bytes), last received/applied server sequence (u64)
0x08AcknowledgeLast applied server sequence (u64)
0x18PongLast processed client sequence (u64): 8 bytes
0x19ErrorCode (u16), message length (u16), UTF-8 message
0x1AHandshakeAckServer version (u8), TLV extensions
0x1BSessionResumedReplayed frame count (u32)
0x20ReplayGapMissing sequence range: from (u64), to (u64)
0x23FlowControlWarningBuffer usage percent (u8), hard-limit flag (u8)

HandshakeAck currently has 41 payload bytes. Each TLV is tag (u16), length (u16), value. Skip unknown tags:

TagValue
1Capabilities (u64)
2Assigned session ID (16 bytes)
3Heartbeat interval in milliseconds (u32)

Capability bits 0–7 indicate session recovery, heartbeat, batch orders, order flags, order query, TLS, mutation deduplication and open-order snapshots respectively. Send heartbeats within the configured timeout.

SessionResumed precedes replay. On ReplayGap, obtain a complete GetOpenOrders snapshot; it restores open order state, not missed settlement events. Reconcile missing executions separately. Do not silently treat a fresh session as recovery of an old one. See client integration and deployment.

Order commands

PlaceOrder (0x01)

OffsetTypeField
0u64Nonzero order ID
8u16Symbol ID
10u8Side: buy 0, sell 1
11u8Order type
12u8Time in force
13i64Limit price; zero for market
21i64Stop price; zero for non-stop
29u64Positive total quantity
37u8Optional flags; absent means zero
38u64Optional GTD expiry; absent means zero
46i64Optional trailing distance; absent means zero
54u64Optional iceberg display quantity; absent means zero

Base payload is 37 bytes; optional fields extend it to 38, 46, 54 or 62 bytes. Include all preceding optional fields when using a later one. GTD requires a nonzero future expiry. Trailing distance must be nonnegative and a positive distance is valid only on stop orders. Positive display quantity is valid only on limit orders. Stop orders require a positive stop price; limit/stop-limit require a positive limit price.

Order types: Limit 0, Market 1, StopLimit 2, StopMarket 3. Time in force: GTC 0, IOC 1, FOK 2, GTD 3. Flags: POST_ONLY 0x01, REDUCE_ONLY 0x02, MAKER_OR_CANCEL 0x04. REDUCE_ONLY is a reserved futures flag; this spot engine does not enforce position reduction. Do not rely on it as an account risk control.

Other commands

TypeNamePayload
0x02CancelOrderOrder ID (u64), symbol ID (u16): 10 bytes
0x03AmendOrderOrder ID (u64), symbol ID (u16), has-price (u8), optional price (i64), has-qty (u8), optional qty (u64): 12–28 bytes
0x07GetOrderStatusOrder ID (u64), symbol ID (u16): 10 bytes
0x09GetOpenOrdersEmpty
0x0BBatchPlaceOrderCount (u8, 1–20), then fixed 38-byte PlaceOrder entries
0x0CBatchCancelOrderCount (u8, 1–50), then 10-byte CancelOrder entries

Amend presence flags are 0 or 1; include at least one changed field. Batch placement requires the flags byte on every entry and cannot carry GTD expiry, trailing distance or iceberg extensions. Batches execute individual items and are not atomic across symbols.

Cancel, amend and status requests are scoped to the requesting session. An order belonging to another session is reported as not found. Durable mutation retries return the original outcome; a retained request ID with a different payload is rejected. Query responses may be regenerated after bounded-cache eviction.

Order events

Fields below are serialized in the listed order, without alignment padding. timestamp is u64, price is i64, quantity is u64, and order/trade IDs are u64.

TypeNameBytesPayload
0x10OrderAccepted16Order ID, timestamp
0x11OrderRejected17Order ID, reason (u8), timestamp
0x12Trade59Trade ID, symbol (u16), price, qty, maker ID, taker ID, maker side (u8), timestamp, trade sequence (u64)
0x13OrderFilled32Order ID, filled qty, price, timestamp
0x14OrderPartiallyFilled40Order ID, filled qty, remaining qty, price, timestamp
0x15OrderCancelled24Order ID, remaining qty, timestamp
0x16OrderAmended32Order ID, new price, new qty, timestamp
0x17StopTriggered24Order ID, trigger price, timestamp
0x1DOrderStatus41Order ID, status (u8), filled qty, remaining qty, price, timestamp
0x1EOrderNotFound8Order ID

One command can emit several events. Continue consuming unsolicited owner events even when no local command is pending. The trade sequence inside Trade is distinct from the frame's server sequence.

Open-order snapshots

TypeNameBytesPayload
0x1FOpenOrdersBegin12Count (u32), snapshot sequence (u64)
0x21OpenOrder60Layout below
0x22OpenOrdersEnd8Same snapshot sequence (u64)

Wait for End with the matching request ID. Validate Begin/End sequence equality and the declared order count before replacing local state. A read timeout is not a valid empty snapshot.

OpenOrder offsets: ID 0 (u64), symbol 8 (u16), side 10, type 11, TIF 12, status 13 (u8 each), price 14 (i64), stop price 22 (i64), total qty 30 (u64), open qty 38 (u64), timestamp 46 (u64), flags 54 (u8), reserved zero bytes 55–59. For an iceberg, open qty includes the hidden remainder. This fixed layout does not include expiry, trailing distance or display size.

Order status values: New 0, PartiallyFilled 1, Filled 2, Cancelled 3, Rejected 4, Triggered 5.

Rejection and error codes

OrderRejected reasons (u8):

CodeReasonCodeReason
0NoLiquidity8SymbolNotFound
1InsufficientLiquidity9TradingHalted
2InvalidPrice10RiskCheckFailed
3InvalidQuantity11WouldTakeMarket
4InvalidLotSize12InternalError
5InvalidTickSize13SelfTradePrevented
6OrderNotFound14InvalidExpiry
7DuplicateOrderId15AmendNotSupported

Protocol Error codes (u16): 1 UnsupportedVersion, 2 SequenceOutOfOrder, 3 HandshakeRequired, 4 InvalidPayload, 5 ServerShuttingDown, 6 Backpressure, 7 HeartbeatTimeout, 8 TlsError, 9 InvalidRequestId, 10 SessionExpired, 11 BufferExhausted, 12 InternalError. Some codes are reserved; their assignment remains part of the wire contract. Handle unknown codes without corrupting framing.

An InternalError is not a successful execution acknowledgment. Reconnect/retry according to the retained mutation identity and recovery contract; do not generate a replacement order merely because delivery failed.

Funded extension

Financial mode reserves message IDs 0x30–0x33 and 0x38, with capability bits 8–11. Their contracts and storage compatibility are described in Financial pilot. Legacy listeners reject these messages; financial listeners reject legacy order admission.

Architecture

The service separates symbol matching from network I/O. In legacy mode each symbol maps to a shard worker; that worker serializes commands, risk decisions and book mutations. Independent legacy symbols have no global execution order. Financial mode uses one serial shard and a durable decision sequence for all configured symbols.

Workspace

CrateResponsibility
me-coreFixed-point types, orders, events, symbols and session IDs
me-bookPrice levels, order pool, stop book and price-time matching
me-enginePer-symbol engine, routing, shard workers, risk/durability orchestration
me-persistJournal encoding, CRC checks and atomic snapshots
me-ioProtocol codec, TCP/UDS, session storage, replay and delivery
me-serverConfiguration, startup/recovery, TLS, HTTP and shutdown
me-financialShared funded-order contracts, decision identities and mTLS transport
me-ledgerExact PostgreSQL accounting, reservations, outbox and settlement
me-gatewayInternal mTLS HTTP API, account permissions and financial recovery
me-riskPer-symbol admission and execution risk policy
me-metricsPrometheus instrumentation
me-auditStructured audit telemetry
me-clockSystem, coarse and CPU-counter clocks
me-benchCriterion benchmark suites
me-datagenSeeded order-flow generator

Matching

The order book uses sorted price levels, FIFO order links and indexed order storage. Crossing orders take the best opposing prices first. Cancels use the order index; price/quantity amendments can alter time priority according to the matching rules. Stops activate from trade prices, GTD orders expire from recorded processing time, and iceberg replenishment participates in the same matching work budget.

Prices are signed 64-bit fixed-point values; quantities are unsigned 64-bit fixed-point values, both with scale 10^8. The binary wire layout is explicitly encoded and is independent of Rust struct layout.

Legacy risk policy runs before admission and also covers amendments and triggered stops. Legacy ownership is based on the client session; its server configuration defaults invariant violations to halting the affected symbol.

Financial orders retain account, reservation, fee and order-version bindings; self-trade prevention uses the account identity. Funded admission and instrument constraints apply, but financial mode does not expose configurable me-risk limits. Its JSON symbol configuration selects the invariant policy, defaulting to strict (panic); the generated pilot explicitly uses strict.

Legacy request path

  1. Decode a frame and validate protocol/connection state.
  2. Check session/request identity and admission capacity.
  3. Route the command to its symbol worker, enforcing session ownership and risk.
  4. Persist the decision/outcome when durability is enabled.
  5. Persist replies and passive owner events in session history before delivery.

Network tasks use blocking-task boundaries for synchronous shard operations. TCP and UDS share codec and session semantics; TLS wraps TCP transport.

Financial request path

  1. Authenticate the service certificate and its account/operation permissions.
  2. Commit the intent, full reservation and stable outbox command in PostgreSQL.
  3. Send the original command bytes to the financial matcher over mTLS.
  4. Commit a matching decision to the durable journal before confirming it.
  5. Apply the whole decision, both counterparties, fees and settlement cursor in one PostgreSQL transaction.

A disconnect preserves the reservation. Outbox retries retain their original IDs and payloads. Duplicate decisions have no financial effect; an identity or lineage mismatch blocks admission until reconciliation. The matcher journal owns executions, while PostgreSQL owns financial accounting. See the financial pilot for the API, limits and operational procedure.

Recovery and observability

Legacy engine journals and the session journal are a single recovery unit. Snapshots are checkpoints; retained decisions reconstruct subsequent state and verify expected events. Startup fails on incompatible configuration, detected corruption or replay divergence. Financial recovery instead pairs the complete financial journal and configuration with a coordinated PostgreSQL backup; financial snapshots are verified against full replay.

Legacy HTTP readiness reflects listener, session-storage and engine health. Intentional symbol halts are reported by status without making the service unhealthy. Gateway readiness also checks database ownership, recovery, reconciliation, settlement lag and disk reserve. Audit telemetry may drop records under pressure and is not the authoritative execution journal. See deployment for the operational contract and HTTP API for legacy endpoints.

HTTP API

This page covers the legacy server's operational listener. Funded order submission, balances, settlement events and financial administration use the separate gateway API, which requires mTLS and explicit permissions.

The HTTP listener uses server.metrics_addr, default 127.0.0.1:9091. It provides no native TLS. Protect it with a private network or authenticated proxy.

MethodPathAuthenticationResult
GET/healthnone200 OK or 503 when unavailable/draining
GET/readynoneSame availability check as health
GET/metricsnonePrometheus text exposition
GET/admin/statusnoneService status and per-symbol trading state
POST/admin/halt/{symbol_id}X-Admin-KeyDurable halt
POST/admin/resume/{symbol_id}X-Admin-KeyDurable resume

Halt/resume routes are not registered when server.admin.api_key is empty; requests then return 404. With a configured key, missing/incorrect credentials return 401. Keys require at least 16 printable, non-space ASCII characters. /admin/status remains public even when a key is configured.

curl --fail http://127.0.0.1:9091/ready
curl --fail http://127.0.0.1:9091/admin/status
curl --fail -X POST -H "X-Admin-Key: $ME_ADMIN_KEY" http://127.0.0.1:9091/admin/halt/0

/health and /ready return plain text: OK on success, or draining / engine unavailable with HTTP 503. They do not return JSON.

GET /admin/status example when the service is ready:

{"status":"ready","symbols":[{"symbol_id":0,"trading_enabled":true}]}

Unavailable/draining /admin/status returns HTTP 503 with {"status":"unavailable"} or {"status":"draining"}. Health also checks trading listeners, session storage and shard workers. A deliberately halted symbol remains operationally healthy.

Halt/resume responses contain symbol_id, action and success. Success returns 200; an unknown symbol returns 404, and a failed engine operation returns 503. Existing orders remain in the book when a symbol is halted.

For order commands and events, use the binary protocol.

Deployment and recovery

This guide describes the legacy session server's single-node deployment, storage compatibility and client recovery. For PostgreSQL accounting, the internal mTLS gateway and coordinated financial backup/restore, use the financial pilot guide. Engine benchmarks exclude durable network service costs.

Build and exposure

Use Rust 1.96 or newer and cargo build --release --locked -p me-server --features tls. Run with --config config.toml. Configuration rejects unknown fields and invalid combinations. TCP and HTTP default to loopback. Non-loopback plaintext TCP requires the explicit server.allow_plaintext_remote = true setting; prefer TLS:

[server]
tcp_addr = "0.0.0.0:9090"
metrics_addr = "127.0.0.1:8080"
shards = 4

[server.tls]
cert_path = "/etc/me/server.pem"
key_path = "/etc/me/server.key"
client_ca_path = "/etc/me/client-ca.pem"

[server.admin]
api_key = "replace-with-a-long-random-secret"

[wal]
enabled = true
mode = "pre"
path = "/data/wal"
snapshot_interval = 100000

Add the required [[symbols]] definitions from the root configuration. Setting client_ca_path requires authenticated client certificates. TLS configuration on a binary without the TLS feature, incomplete certificate settings, and unreadable/invalid credentials prevent startup before trading listeners are exposed. A session ID is a bearer credential; TLS does not replace account authorization at the gateway. Protect HTTP metrics and admin access separately: this listener does not implement TLS. An empty admin key disables mutations; configured keys must contain at least 16 printable non-space ASCII characters.

The Dockerfile builds TLS support, runs as UID 10001, and checks /ready on port 8080. Mount a persistent writable /data volume and a read-only configuration/certificate directory. Its default loopback TCP binding requires an explicit deployment configuration for remote clients. With its ENTRYPOINT, pass --config /etc/me/config.toml --metrics-addr 127.0.0.1:8080 as container arguments, without another me-server executable. Restrict port publishing to the intended network. The mounted data directory must be writable by UID 10001.

Durability and recovery

Keep WAL enabled for durable operation. Both pre and post modes synchronously persist mutation decisions and their outcomes before replying. Replay uses the stored decision, original ownership, processing time, expiration metadata, and expected events; it does not turn rejected or unauthorized commands into privileged successful commands.

Engine journals and sessions.wal form one recovery unit. Session admission, request fingerprints, batch intents, replies, and acknowledgments are journaled. Never delete or replace only one of these files. Missing session history for an existing engine history prevents startup. Journal files containing bearer credentials are restricted to owner read/write permissions. A writer lock prevents two engines from recovering or mutating the same journal concurrently.

Snapshots are checkpoints. The complete append-only decision history is retained: snapshot creation does not truncate the journal. A corrupt snapshot can be bypassed only when complete validated history can reconstruct state. Detected engine journal corruption, incompatible configuration, or replay divergence prevents startup. The session journal recovers an incomplete trailing frame at the last complete record. CRC and contiguous sequence validation do not prove that entire trailing records were never deleted; consistent whole-directory backups and storage integrity remain required. Symbol/risk configuration and shard topology are recorded; incompatible changes prevent recovery. Pin shards instead of relying on machine-dependent automatic CPU counts.

Upgrade boundary: old command-only/compacted journals are not silently migrated into the decision format. Do not replace the binary over an existing legacy data directory and assume compatibility. Stop intake, reconcile outstanding orders and executions with the upstream ledger, preserve a complete backup, and use an explicitly validated migration or a reconciled empty book. There is no automated legacy migration or online resharding tool. The atomic snapshot response adds a session-journal record variant: after the new binary writes one, an older binary cannot read that journal. Rollback must use a compatible reader or a reconciled backup; never restore an old backup over acknowledged new trades.

For backups, stop intake and shut down cleanly, then copy the whole data directory with its permissions and deployment configuration. Test restoration in an isolated environment before relying on a backup. A live copy of individual files is not a consistent backup.

Client recovery contract

Protocol v2 uses a 22-byte header and client request IDs. Persist the session ID and last applied sequence from the replay stream on the client. Reconnect by resuming that session; concurrent use of the same session is refused. Retrying an identical durable mutation returns its original outcome; reusing a retained request ID with a different payload is rejected. Read-only query responses have a bounded cache and can be regenerated after eviction.

The replay stream includes both order/query responses and positive-sequence control frames, as described in the protocol. Replayed frames retain their original sequence; never apply them twice. Sequence zero is out-of-band and is not acknowledged. SessionResumed precedes replay with sequence zero. HandshakeAck, Pong, ReplayGap from ResumeSession and some Error frames in the active-session response path receive positive server sequences and must be processed before advancing the cursor. ReplayGap emitted during pending delivery instead uses sequence zero and is not journaled. Passive fills, trades, and stop events use request_id = 0 and are delivered to their owners, including when the owner reconnects later. Preserve those events while assembling a snapshot and commit its cursor only after the complete response validates.

On ReplayGap, request GetOpenOrders. Complete snapshots are delivered in bounded write chunks even when larger than the replay ring. A snapshot is limited to 8 MiB of encoded frames, enough for the 100,000 admitted orders of one session; oversized snapshots are refused before journal mutation. A complete snapshot is persisted as one session-journal record before delivery; interruption during its append does not recover a prefix as a completed snapshot. The per-session query-response cache has a 16 MiB byte budget, with query responses and their admission metadata evicted together. This does not evict durable mutation decisions. An open-order snapshot restores current order state, not missing historical settlement events. Reconcile those against an authoritative execution record before resuming financial processing. The example clients demonstrate submission; they are not complete account/settlement recovery services. The Go SDK provides a separate recovering client with durable ResumeSession, receive cursors and original-request retries. Its ReplayGap state requires reconciliation against an authoritative execution source before financial processing resumes.

Batches retain individual durable item identities and recover partially completed execution without repeating completed items. They are not an atomic transaction across symbols. Per-symbol execution and delivery are serialized; there is no global order across independent symbols.

Capacity and risk policy

Request history and the append-only journals currently grow with activity. Replay buffers are bounded, but total durable request history is not a constant-memory store. Monitor process memory, disk space, write latency, and restart duration; provision capacity and schedule reconciled maintenance. Online history compaction/retention is not implemented. Benchmark the durable path on the intended filesystem and workload before setting an SLA; synchronous persistence changes the cost relative to an in-memory benchmark.

Session admission is bounded: at most 10,000 sessions; each session has 100,000 place/amend units and 16 MiB of admitted mutation payload, with a separate 100,000-unit cancellation reserve. Batches count individual items. Invalid/unauthorized cancellation attempts do not consume that reserve. Existing request retries remain usable. Unused idle sessions can expire; sessions with durable activity are retained to preserve ownership and idempotency. Plan session lifecycle and capacity at the gateway; expiration is not a way to discard active trading history.

Risk checks cover amendments and activated stops as well as placements. A market order requiring a reference price fails closed when none is available; seed symbols.risk.reference_price explicitly or establish a traded reference. Hard notional checks use a conservative execution-price bound from the book and total quantity, including hidden quantity. They can reject an IOC that would only partly fill. With a hard notional cap, amendments after any fill may only decrease or preserve both price and quantity; increases return AmendNotSupported because historical filled quote notional is not an account ledger. Zero rate limit disables that limit. Position limits without an account ledger are unsupported and rejected rather than advertised as enforced.

Matching work limits

A matching command has a shared budget of 4,096 fills, including triggered orders and iceberg replenishment. An order whose predicted matching work exceeds the remaining budget is rejected before that matching pass mutates the book; FOK does not partially execute. An iceberg may contain at most 4,096 display slices. Each symbol may have at most 4,096 live pending stops and 4,096 live GTD orders. These limits apply alongside any stricter configured risk limits and are checked during snapshot restoration. Retired/cancelled orders release their capacity.

The preflight is conservative and can reject work that a less conservative simulation might admit. Existing snapshots above these limits are rejected. Journals created with different matching semantics, including the former delayed iceberg refill behavior, may fail event-equivalence replay; validate upgrade and reconciliation against a copied data directory before deployment.

Matching corrections also preserve FIFO after snapshot restoration, remove the full visible remainder when an amendment cancels a filled-down order, and consume each trade price only once when advancing trailing stops. Journals containing decisions produced by the former behavior can fail equivalence replay. Validate the new binary against a copy of existing storage before upgrading; do not discard or rewrite acknowledged executions to bypass a mismatch.

These bounds prevent a tiny display quantity or a large stop/expiry wave from expanding one command into an oversized durable decision. They are service capacity limits, not financial account limits. Gateway admission and capacity planning must account for them.

Health and shutdown

/health and /ready return 503 while draining, before configured trading listeners bind, or when session storage/engine recovery/workers fail. An intentionally halted symbol remains operationally healthy; /admin/status reports its actual halted state. Halt/resume state is durable. SIGINT/SIGTERM closes intake and drains connections within the configured timeout; HTTP shutdown is bounded as well. A failed durable write stops further safe processing rather than acknowledging an unpersisted result.

The default log filter is info, including audit events and storage/network warnings. RUST_LOG overrides it; excluding the audit target deliberately suppresses audit telemetry. Asynchronous audit telemetry can drop records under pressure; monitor me_audit_dropped_total and me_audit_disconnected_total. It is not the authoritative durable execution journal. The binary audit representation uses explicit serialization and does not expose struct padding.

The legacy session service requires an external account ledger and settlement layer. The separate financial pilot supplies PostgreSQL balances, reservations and settlement with manual maintenance and backup/restore procedures. Neither mode provides replication, consensus, automatic failover or automated disaster-recovery orchestration. Passing local tests does not establish those guarantees.

Verification

cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
cargo test --workspace --all-features --locked
cargo build -p me-server --features tls --locked
ME_TEST_TLS=1 python3 scripts/runtime_smoke.py
python3 -m unittest discover -s examples/python
cargo test --manifest-path examples/rust/Cargo.toml --locked
(cd clients/go/meclient && go test -race ./...)
(cd examples/typescript && npm ci --ignore-scripts && npm test)
cargo audit

Runtime tests start actual processes, exercise TCP and mTLS, kill/restart the server, resume sessions, verify ownership/cancellation and idempotent replies, and check readiness/startup failures. Additional Rust integration tests cover UDS, replay, journal corruption, risk boundaries, and partial-batch recovery.

Monitoring example

Set GRAFANA_ADMIN_PASSWORD to a unique secret, then run docker compose -f monitoring/docker-compose.yml up -d. Grafana is published only on 127.0.0.1:3000; Prometheus is on 127.0.0.1:19090, leaving port 9090 for trading. No default Grafana password is supplied.

The sample scrape target is host.docker.internal:9091. It must reach the engine HTTP listener from the container network: loopback binding on a Linux host is not reachable through the bridge gateway. Bind HTTP to a dedicated private interface reachable only by your monitoring network, or use an authenticated private proxy and update the target. Do not expose the unauthenticated metrics endpoint publicly. Validate up{job="matching-engine"} == 1 after deployment. These rules require an Alertmanager deployment for notifications; the example does not configure one.

Benchmarks

Criterion suites measure the matching engine in isolation. They do not include TLS, network delivery or the durable server's synchronous journal writes.

cargo bench --locked -p me-bench --bench latency
cargo bench --locked -p me-bench --bench throughput
cargo bench --locked -p me-bench --bench e2e
cargo bench --locked -p me-bench --bench stress
cargo bench --locked -p me-bench --bench realistic

Record the Git revision, Rust version, CPU, operating system, compiler options and workload. Run on an otherwise idle machine with a consistent power policy. Criterion writes reports under target/criterion; compare repeated runs rather than a single best value.

me-datagen creates reproducible order streams with --seed. Inspect its options with cargo run --locked -p me-datagen -- --help. Record symbol count, order mix, book depth and seed with any results.

For service measurements, include transport, journal sync, client event application and restart/replay cost. Test both steady load and bursts on the intended filesystem. Report percentile latency, throughput, errors, memory and disk growth. No benchmark number in this repository is a deployment SLA.

Financial pilot validation

Validation of v0.2.0-rc.1 on 2026-10-15. This is a local financial pilot without real assets, public access or automatic failover.

Revision and environment

The tested Rust/Go service source is commit fdc47efe35374cc7b25fc1807c94e1a780b534a4. Commit 67bf17c90b9262f9c4e2220af7a1059f02d0f227 adds backup checksum verification and documentation corrections; it does not change those binaries. Commit c0cf702e8aa74ab825db834dbe271f38a3e06cea makes runtime tests wait for protocol completion and adds operator funding steps. The release tag identifies the complete source and handbook.

The hour run uses release builds with all workspace features on an Apple M5 Pro (18 logical/physical CPUs, 24 GiB RAM), macOS 26.6.2 arm64, Rust 1.98.1 / LLVM 22.1.8. Matcher and gateway run natively. PostgreSQL 17.11 runs on Docker Desktop 29.7.2 with 8 vCPUs and 14,636,363,776 bytes of VM memory, using a private persistent volume. This shared workstation also ran review and validation tasks, including a diagnostic soak during the first part of the measurement; it was not an isolated capacity benchmark.

Correctness and recovery

CheckResult
Rust workspace, all features674 tests passed; 11 PostgreSQL tests run separately; one subprocess helper intentionally ignored
PostgreSQL integration11 passed: exact arithmetic, balanced immutable postings, frozen fees, reservations, request conflicts, concurrent funds, settlement and rollback checks
Financial order model130 order/TIF/flag and lifecycle cases, including expected rejections; 185 trades independently checked for both accounts and fees
GTD recovery600 due orders across two instruments, bounded expiry decisions, restart between batches and no execution of expired orders
Process/network faultsUnsent outbox; WAL confirmation lost before settlement; original-byte retry; duplicate decision; restart after settlement; partial iceberg, batch, amend, trailing stop and GTD recovery
Resource/integrity faultsActual ENOSPC on isolated 8 MiB tmpfs; reserve retained and retryable; incomplete tail recovery; complete journal corruption and source rollback fail closed
Go SDKRace tests, actual TLS/server reconnect, slow continuous replay, checkpoint subprocess crash, replaced-lock detection and mandatory ReplayGap reconciliation
OperationsPostgreSQL outage, exclusive gateway lease, mTLS ACLs, local Alertmanager delivery, coordinated backup into a new database/directory, overwrite refusal and checksum/model validation
Legacy integrationsRust, Go, Python and TypeScript examples; 30 TLS/runtime tests (two intentional example skips); unchanged v2 payloads and legacy journal/snapshot regression tests
Build and dependenciesFormatting, Clippy with warnings denied, release build, rustdoc, mdBook, Docker and dependency audit passed
FuzzingAddressSanitizer decoder runs: 6,208,681 pending-state and 6,489,763 handshaked-state executions, 61 seconds each, no crashes
Review and secret scanSeven supervised revmux rounds, four reporting lenses per round without degraded participants; significant fixes re-reviewed. Git history scan found no secrets. This is not an external security audit.

Codebase Memory was used for structural discovery with path coverage checks. Its 2026-10-10 index predates the financial modules and excludes documentation/scripts; those areas and stale ranges were read directly. Clean graph coverage was not treated as proof of completeness.

Linux CI also runs the PostgreSQL tests, full financial matrix, short soak, real ENOSPC and Compose recovery. See the service validation run. The final revision must pass CI before publication.

One-hour full-path measurement

MeasurementResult
Duration3600.092 s
Settled trades13,354
Confirmed placement commands26,708
Observed commands/s7.419
Complete-pair latency p50 / p95 / p99251.108 / 364.452 / 375.420 ms
Midpoint restart to readiness and receipt replay0.444 s
Errors0
Matcher journal growth42,576,445 bytes
Final maintenance snapshot14,413,961 bytes
Final engine directory56,990,754 bytes
PostgreSQL relation growth195,624,960 bytes

Machine-readable results and binary SHA-256 digests.

The single driver submits a resting buy then a crossing sell for 0.00001 BTC at 100 USDT, using separate funded accounts. Maker fees are 10 bps and taker fees 20 bps. Each request establishes a new mTLS connection. Timing includes both HTTP placements and polling until their intents settle; it measures a complete pair, rather than one matching operation. Gateway polling has a 100 ms interval. At most one resting order is present per pair; this does not measure large books or concurrent stop/iceberg bursts. Throughput is observed command throughput under this sequential workload, not a saturation limit.

At the midpoint the driver kills both processes, restarts them and retries the original requests. The restart timer ends after readiness and verification of both original receipts; completion of both orders is checked separately before the pair is counted. Final decimal balances, fees, zero outstanding reserves, the maintenance watermark and the accounting audit must agree. PostgreSQL size growth counts tables, indexes and TOAST in the test schema; it excludes PostgreSQL WAL and volume overhead. Matcher journal growth is measured separately. Both histories remain retained; no online compaction is implemented.

Reproduction

Use a disposable PostgreSQL database and pass its URL through a private environment:

cargo build --release --workspace --all-features --locked
cargo test -p me-ledger --test postgres --locked -- --ignored
python3 scripts/financial-matrix.py --bin-dir target/release --output /tmp/pilot-matrix
python3 scripts/financial-faults.py --bin-dir target/release --output /tmp/pilot-faults
python3 scripts/financial-soak.py --bin-dir target/release --seconds 3600 --output /tmp/pilot-hour

These commands require LEDGER_TEST_DATABASE_URL; the scripts create isolated schemas. Retain their reports and private state outside Git. For actual disk exhaustion and the Compose backup rehearsal, follow the pilot guide. Generated test identities expire after two days.

Release boundary

Start with a new financial book and ledger. Financial storage/schema version 1 has no legacy-account migration or automatic downgrade. Existing v2 session payloads and legacy storage codecs remain unchanged. Financial messages require capability negotiation and mTLS. Protected market prices, immutable nonnegative quote fees and conservative amendment reserves are mandatory.

One active matcher and gateway are supported. Financial mode does not expose configurable me-risk limits. Snapshots are checked against full journal replay and do not accelerate recovery. Funding and withdrawals record accounting entries only. Production alert destinations, real asset transfers, public APIs, replication, automatic failover and online compaction are outside this release.