OptionChain-Simulator API and Architecture
System Architecture
Two REST surfaces over one set of layers. v1 serves a single expiration per
request and stamps it with the wall clock; v2 serves a rolling inventory of
absolute expirations on a simulated clock. They share the seeded walk and
the error boundary, and nothing else — separate session types, separate
stored schemas, separate stores.
flowchart TD
Client[Client]
subgraph api["api — REST, f64 at the boundary"]
V1["/api/v1/chain"]
V2["/api/v2/simulations"]
Export["/api/v2/simulations/{id}/export"]
end
subgraph session["session — lifecycle, effective parameters"]
SM[SessionManager]
SIM[SimulationManager]
end
subgraph domain["domain — private, seeded, pure"]
Simulator[Simulator + Walker]
Tape[FactorTape]
Planner[RollingPlanner]
Series[SeriesBuilder]
end
subgraph infra["infrastructure — adapters"]
Redis[(Redis)]
Mongo[(MongoDB)]
CH[(ClickHouse)]
end
Client --> V1 & V2 & Export
V1 --> SM --> Simulator
V2 --> SIM
Export --> SIM
SIM --> Tape
Tape --> Series
Planner --> Series
SM -.sessions.-> Redis
SIM -.simulations.-> Redis
SM -.events.-> Mongo
Simulator -.historical prices.-> CH
SIM -.snapshots, opt-in.-> CH
Export -.persisted rows first.-> CH
domain is a private module: the walk, the tape, the planner and the
snapshots are implementation, and the REST contract is what is public. The
dependency arrows only ever point down — an infrastructure adapter that
imported api would invert the layering, which is why the persistence layer
carries its own row types instead of naming the domain snapshot.
Session State Transitions
stateDiagram-v2
[*] --> Initialized: POST /api/v1/chain
Initialized --> InProgress: POST /api/v1/chain/step
InProgress --> InProgress: POST /api/v1/chain/step
InProgress --> Modified: PATCH
Modified --> InProgress: POST /api/v1/chain/step
InProgress --> Reinitialized: PUT
Modified --> Reinitialized: PUT
Reinitialized --> InProgress: POST /api/v1/chain/step
Initialized --> [*]: DELETE
InProgress --> [*]: DELETE
Modified --> [*]: DELETE
Reinitialized --> [*]: DELETE
GET /api/v1/chain is a safe, repeatable peek and does not appear here because it
never changes the session state — only POST /api/v1/chain/step advances the cursor.
A v2 simulation walks a smaller machine, because it is immutable after
creation: there is no PATCH or PUT to reach Modified or Reinitialized,
and a stored document in either state is rejected on load rather than
served.
stateDiagram-v2
[*] --> Initialized: POST /api/v2/simulations
Initialized --> InProgress: POST /{id}/step
InProgress --> InProgress: POST /{id}/step
InProgress --> Completed: POST /{id}/step (last)
Initialized --> [*]: DELETE or idle TTL
InProgress --> [*]: DELETE or idle TTL
Completed --> [*]: DELETE or idle TTL
The state and the cursor are validated together: Initialized only at step
zero, Completed only at the horizon, InProgress strictly between them.
GET /{id}/snapshot and the export appear nowhere here — neither moves the
cursor, and the idle TTL is measured from the last write, so peeking does
not keep a simulation alive.
API Request Flow
sequenceDiagram
participant Client
participant API as REST API
participant SM as Session Manager
participant SS as Simulator Service
Client->>API: POST /api/v1/chain
API->>SM: Create new session
SM->>SS: Initialize simulation
SS-->>SM: Initial state
SM-->>API: Session created (id: abc123)
API-->>Client: 201 Created (session details)
Client->>API: POST /api/v1/chain/step
API->>SM: Advance one step
SM->>SS: Advance simulation
SS-->>SM: Step data
SM-->>API: Chain data
API-->>Client: 200 OK (Chain data)
Client->>API: GET /api/v1/chain
API->>SM: Peek current step
SM->>SS: Read current snapshot
SS-->>SM: Step data (no advance)
SM-->>API: Chain data
API-->>Client: 200 OK (same snapshot, repeatable)
A v2 advance does more work behind the same shape. The tape is built on
first use rather than at creation, chains are priced per snapshot from a
factor row and the planner's live expirations, and — when persistence is on
— the served step is queued for the warehouse after the cursor commits,
so the write is never on the response's clock.
sequenceDiagram
participant Client
participant API as REST API
participant SIM as SimulationManager
participant Tape as FactorTape
participant Series as SeriesBuilder
participant CH as ClickHouse
Client->>API: POST /api/v2/simulations
API->>SIM: Resolve seed, start, interval, schedules
SIM-->>API: Simulation created (every replay input echoed)
API-->>Client: 201 Created
Client->>API: POST /api/v2/simulations/{id}/step
API->>SIM: Advance (expected_step precondition)
SIM->>Tape: Build once, then cache (single flight)
Tape-->>SIM: Factor row for the cursor
SIM->>Series: Price the live expirations at that row
Series-->>SIM: Snapshot
SIM->>SIM: Commit the cursor (compare-and-swap)
SIM-->>API: Snapshot + new cursor
API-->>Client: 200 OK
SIM--)CH: Queue the served step (detached, best effort)
Client->>API: GET /api/v2/simulations/{id}/export
API->>CH: Read the persisted range
CH-->>API: Rows for the steps it has
API->>Series: Replay whatever is missing
API-->>Client: 200 OK (streamed JSON or CSV)
REST API Endpoints
The OptionChain-Simulator exposes the following REST API endpoints:
| Method |
Endpoint |
Action |
Description |
| POST |
/api/v1/chain |
Create Session |
Creates a new simulation session |
| GET |
/api/v1/chain |
Read Current Step |
Returns the snapshot the next advance will serve (safe, repeatable) |
| POST |
/api/v1/chain/step |
Advance Step |
Serves the snapshot at the cursor (index 0 first), then advances |
| PUT |
/api/v1/chain |
Replace Session |
Completely replaces session parameters |
| PATCH |
/api/v1/chain |
Update Parameters |
Updates specific session parameters |
| DELETE |
/api/v1/chain |
Delete Session |
Terminates and removes a session |
| GET |
/health |
Liveness |
The process is alive; always 200, no dependency touched |
| GET |
/ready |
Readiness |
200 when every configured dependency answers, 503 naming those that did not |
Probes
The two answer different questions, and conflating them is how one outage
becomes two. /health says the process is alive: it touches nothing, so a
Redis hiccup can never get a healthy instance restarted. /ready says this
instance can take work, and it asks: Redis and MongoDB always, ClickHouse
when snapshot persistence is enabled, each under a 2-second bound and all of
them at once. A 503 body names every dependency and, for the failing ones, a
fixed category: unreachable or timed_out. Never a driver's own words —
the endpoint is unauthenticated, and a server message can carry internal
hosts, paths and tokens no redaction reliably recognises, so the full
explanation stays in the service's log. Nothing is cached, so an instance
whose Redis came back reports itself ready again without a restart.
That last claim is the one an orchestrator acts on, so it is proven by a
fixture rather than asserted: scripts/replica_isolation_test.sh runs two
replicas over shared dependencies, disconnects ONE of them from the Redis
network — the dependency is never stopped, which would break both — and
requires the isolated instance to answer 503 naming Redis while its
neighbour still answers 200. Each answer is attributed by its
x-ocs-instance header, so the assertions are about a named replica rather
than about whichever one a balancer chose, and the recovery is asserted by
reconnecting the network and requiring the SAME instance id to report
itself ready again: an unchanged id is a process that was never restarted.
CI runs it on a change to the probes, to what they probe, or to how the
service is packaged.
An exported value renders by NUMBER, not by how it was stored. A decimal is
a mantissa and a scale, so one value has several forms, and the warehouse
round trip changes the form: a value is scaled out to the column's
twenty-eight decimals going in and comes back with its trailing zeros
stripped. Converting either form straight to the wire's f64 reads the
mantissa and can land on adjacent floats, which made an export of a tape
whose rows had been filed differ in a digit from the same tape replayed, and
broke byte-identical repeats on a deployment with persistence on (issue
##152). Every conversion in the export normalises first, so the two agree.
Whether a deployment persists its snapshots is visible in the readiness
body: the warehouse probe exists only when the manager has a warehouse, so
a clickhouse dependency there is persistence being on. The integration
suite reads it and says which of the two export paths a run exercises,
rather than testing one and reporting as though it had covered both.
Both are unversioned, unauthenticated, and excluded from the request
metrics: an orchestrator polling forever would otherwise add a constant to
every series and a flood of 503s to the error series while a dependency is
down. Docker/docker-compose.yml points its backend healthcheck at
/ready, so docker compose up -d reports the service healthy only once it
can actually serve.
Metrics are per process
/metrics serves the metrics of the INSTANCE that answers. That is what a
Prometheus exposition is, and it is worth stating because this service is
meant to run replicated: the numbers there are one instance's share of the
traffic, never the deployment's total.
So a replicated deployment is scraped per replica, each container its
own target with its own instance label, and totals come from summing
across that label. Scraping one load-balanced address instead returns
whichever replica answered that scrape, which looks like this:
api_requests_total{endpoint="/metrics",method="GET",status="200"} 4
api_requests_total{endpoint="/metrics",method="GET",status="200"} 8
api_requests_total{endpoint="/metrics",method="GET",status="200"} 5
api_requests_total{endpoint="/metrics",method="GET",status="200"} 9
Two replicas answering in turn. Prometheus reads every apparent drop as a
counter reset, so rate() over such a series is not wrong so much as
meaningless. A single scrape endpoint for a whole deployment is an
aggregator's job, not something this service pretends to do.
What aggregates and what does not depends on the kind of metric. Counters
and histograms do, as sum(rate(..)) across the instance label. Gauges do
not: active_sessions is each process's own count, and a session created
through one replica and deleted through another leaves the first replica's
gauge untouched, as do reaps and restarts. The live-session total is a
question for the store, not for a gauge.
What a client is SERVED never depends on which instance answers: the stores
are shared and every write goes through an atomic Redis script. What is per
process is how much work the deployment repeats and how its numbers must be
read.
The pricing bound is the deployment's
OCS_MAX_CONCURRENT_PRICING_JOBS used to bound one process, so two replicas
ran twice the configured jobs and an operator learned it when the host
saturated. The instances now hold leases in a shared Redis set, taken and
released around the same work, so the number is what the DEPLOYMENT runs.
The lease expires on its own, which is what stops a killed instance from
holding one forever, and a job still running renews it, so the sweep cannot
reap the lease of work that is still burning the CPU it was leased for. The
clock the expiry is measured on is the Redis server's, because the whole
point is that several machines order each other's leases and their own
clocks do not agree well enough for that.
A gate that is up and FULL makes the caller wait, cancellably, for as long
as it takes. Falling back there would bypass the deployment-wide bound
exactly under the sustained load it exists for. Only a gate that cannot be
REACHED falls back to the per-process semaphore: that is the bound the
service always had, and pricing unbounded would be a worse answer to a
Redis outage than pricing more concurrently than configured.
Both permits are held by a task that outlives the request, because a
blocking job keeps running when the client that asked for it goes away.
Releasing them on cancellation would leave that CPU work running outside
the bound it was admitted under.
Built tapes are shared
The factor tape is the expensive thing to rebuild — it walks every step —
and it is a pure function of the stored parameters and the seed. It is
therefore written to Redis once built, under a key carrying the snapshot
generation and a fingerprint of the parameters, and read from there by any
instance that needs it. A deployment behind a balancer stops rebuilding on
whichever instance takes the next step.
The in-process cache stays in front of it: a local hit costs nothing where
a shared one costs a round trip, and OCS_MAX_CACHED_TAPES now bounds both
— the deployment's shared cache as well as each instance's own map, with
the least recently used evicted first and a deleted or reaped simulation
taking its tape with it.
A failure of the shared cache is a miss rather than an error, so a cache
command that fails costs a rebuild and not a request. That promise is about
the CACHE, not about Redis: the simulation itself is read from the same
Redis first, so an outage fails there, before the cache is consulted at
all. What degrades is the saving, not the service's dependence on its
store.
The snapshot cache is still per instance (issue #136's second item), which
is a smaller loss: rebuilding a snapshot from a cached tape is far cheaper
than building the tape.
Only ONE instance builds a given tape. A build is claimed in the same
Redis before it starts, so the coalescing that stops N concurrent readers
of one process starting N identical builds now spans the deployment. The
claim expires, and a waiter that does not see the tape in time builds it
anyway: an instance killed mid-build costs a duplicated build rather than
a request that never answers.
Step cursor semantics (serve-then-advance): current_step is the 0-based index
of the NEXT snapshot to serve. POST /api/v1/chain/step