Wiki Design
Design decisions
The architecture decision record of Mirexa — each decision with its context, reasons, the alternatives it refused, its consequences, and the source and tests that hold it in place.
This page records the decisions that shape Mirexa: what was chosen, why, what was considered and refused, and what the choice costs. Many of Mirexa's most important properties are refusals — a feature deliberately not built because it would have made a guarantee false — so the refused alternatives are recorded as carefully as the choices.
Every entry describes the system as it stands at the commit in the front matter. Where a
decision was later reversed, the entry describes the current one. Each entry has a stable
heading anchor, so other pages can link to it, for example
design/decisions.md#raft-for-the-control-plane-only.
Each entry has the same six parts: Decision, Context, Reasons, Alternatives refused, Consequences, and References (the source that implements it and the tests that would fail if it changed).
Index
Data model and storage
Market closures are not fillable
Decision. A gap whose reason is market closure (OFF_TIME) can never be filled by a
correction. Ordinary data that simply arrives for closed hours is still accepted.
Context. Mirexa classifies every hole in a stream as either time the market was shut or data that was lost. Operators fill lost data from other sources.
Reasons. There is no data for hours an exchange was closed, so anything written there is fabricated, permanently, into the one store built to tell a closure from a loss. A "filled" weekend is indistinguishable afterwards from a weekend that traded. Real candles arriving for "closed" hours are different: they are evidence the calendar is wrong (an extended session, a changed holiday), and discarding market data because configuration disagrees with the exchange is the worse error.
Alternatives refused. Enforcing fillability only in the dashboard (anything speaking the wire skips it, and it races a reclassification). Deriving fillability in each client from the gap's reason (one client eventually draws a fill button over a weekend).
Consequences. GapRange.Fillable is the one definition; the node refuses a correction or
restatement landing in a filed closure before writing anything; clients render the
fillable field they are sent.
References. types.GapRange.Fillable,
LiveStreamWriter; tests TestGapRange_Fillable,
TestCorrection_RefusesToFillAMarketClosure,
TestIngest_APlainWriteFillsAStoredOutageButNeverAMarketClosure. See
Gaps and trading calendars.
A filled gap is closed, not deleted
Decision. When a correction fills an outage, its gap record is marked CLOSED after the
data is durable. The record is kept.
Context. A fill updates two things: the data (a patch chunk) and the gap index.
Reasons. The record that a range was back-filled is provenance this engine exists to keep. Closing runs last, after the data is durable: the reverse order could report a hole repaired that a crash then loses. Closing requires the fill to contain the gap; a partial fill leaves it open, overstating what is missing — the safe direction.
Alternatives refused. Deleting the record; closing on overlap rather than containment.
Consequences. Missing-time statistics count only open gaps; a closed gap stops counting as missing.
References. /internal/ingestion/dispatcher.go;
tests TestDashboard_DiscoverGapThenFillItThenItIsGone,
TestGapIndexStatistics_ClosingAGapDropsItsMissingTime. See
Finding and filling gaps.
Calendars are stream metadata
Decision. A stream's trading calendar (weekly hours and declared closures) is stream
metadata, set live through the control API or mirexa-cli calendar set, and a change
re-files every gap of the stream at once.
Context. Gap classification depends on knowing when a market is open.
Reasons. A calendar belongs to the stream it describes and travels with it to copies; a config file is per node and needs a restart. Re-filing at once means the gap index never holds classifications computed against two different calendars.
Alternatives refused. A streams: section in the node's config file (removed);
prospective-only calendar changes that leave old gaps classified by the old calendar.
Consequences. Changing a calendar can move many gaps between OPEN and OFF_TIME
immediately; a gap already filled with data is never touched.
References. /cmd/cli/calendar.go,
/internal/types/stream.go; test
TestCalendar_AChangeRefilesEveryGapAtOnce. See
Gaps and trading calendars.
A plain write onto history is a restatement
Decision. A live batch containing bars older than the hot cache can hold is not refused: each bar goes where it belongs — a patch for a bar in a chunk, a new version for a bar in the cache, an append for a new bar. A bar identical to what is stored is skipped.
Context. Clients cannot see where a node keeps a given bar (cache or chunk), and the boundary moves with every flush.
Reasons. Making a client know the storage boundary pushes an internal detail into every caller. Skipping identical bars makes a replay free (no patch written, nothing pushed to subscribers), so reconciling an ambiguous write is simply re-sending it.
Alternatives refused. Refusing any bar below the cache's window. The explicit correction flag remains as the strict form: it refuses a bar past the stream's newest data.
Consequences. Still refused: a write into a filed closure, a bar off its chunk's grid,
and a hole older than every chunk (only the history route installs those, and the node says
so with HistoryRequired). mirexa_ingestion_restatements_total{outcome} counts patched and
unchanged bars.
References. LiveStreamWriter.restate in
/internal/ingestion/dispatcher.go; tests
TestIngest_APlainBatchOverFlushedCachedAndNewBarsLandsWhole,
TestIngest_ResendingStoredBarsWritesNoPatch,
TestCorrection_AFlaggedCorrectionRefusesABarPastTheStreamsNewestData. See
Corrections, restatements and history.
Corrections are cumulative patches
Decision. A correction to a flushed chunk writes a patch chunk that names its base, sits directly after it in the stream index, and holds every correction made to that base so far. A patch of a patch is refused.
Context. Chunks are immutable once installed; corrections must survive restarts and replicate to copies byte for byte.
Reasons. A read stays "base plus at most one patch", and the replication seed ships the same artifacts unchanged. Overlaying every patch on read would make read cost grow with a chunk's correction history.
Alternatives refused. Rewriting the base chunk in place (breaks the immutable-artifact model replication depends on); stacking patches and overlaying them all on read.
Consequences. Each correction rewrites the whole cumulative patch for its base; a patch entry carries its own size and record count so the seed can verify it.
References. ChunkPersister.PersistCorrection;
tests TestCorrection_SecondCorrectionToOneChunkIsServed,
TestStreamIndex_SearchesSeeEveryBaseWhenPatchesExist. See
Chunks and compression.
Late ticks are stored
Decision. A trade older than its stream's newest flushed tick chunk (a late print) is stored: it rejoins the chunk its time belongs to, rewritten under a new sequence number in one index write.
Context. Ticks have no admission window. Before this, a late tick wedged every later flush of its stream.
Reasons. A late print is real market data. Refusing it loses data; accepting it and failing to store it is worse.
Alternatives refused. Refusing ticks older than the last flush.
Consequences. Tick sequence numbers may have holes. The cost of a feed that prints late constantly — a whole chunk rewritten per flush — is unmeasured.
References. /internal/storage; tests
TestTickStorage_ALateTickIsStoredInTheChunkItsTimeBelongsTo,
TestTickStorage_ACopyInstallsARewrittenChunk. See Ticks.
Hot-cache size is per stream
Decision. Each stream's in-memory hot cache is sized from its timeframe — a configured
time span divided by the stream's interval, at least 2,048 slots — capped by
cache_arena_capacity, and overridable per stream (mirexa-cli cache set).
Context. One slot count for every stream gave an hourly stream years of cache and a one-second stream hours.
Reasons. Memory should follow what a stream needs to hold, not a global constant.
Alternatives refused. A single global arena capacity for all streams.
Consequences. The cache size is also the widest live batch a stream accepts; a wider
batch is refused as a bad batch (ErrBatchTooWide) before anything is logged. Code that
predicts the next arena must read the cache's sizing, not the current arena's capacity.
References. /internal/cache, /cmd/cli/cache.go;
tests TestStreamCache_AdmissionPredictsTheArenaAPendingSizeGives,
TestStreamCache_ASizeChangeOnAnEmptyCacheTakesEffectAtOnce,
TestIngest_ABatchWiderThanTheArenaIsRefusedNotShed. See
The hot cache.
Acknowledge after fsync, with group commit
Decision. An INGEST_ACK is sent only once the batch's write-ahead-log record is
fsynced. Concurrent writers share fsyncs (group commit) through wal.Writer.AwaitDurable.
Context. An acknowledgement is a durability receipt; clients discard data they have been told is safe.
Reasons. Acking from a buffer makes the ack a lie for exactly the crash it is meant to survive. Group commit keeps the per-batch cost far below one fsync each under concurrency.
Alternatives refused. Acknowledging on enqueue; per-write fsync without batching.
Consequences. Write latency includes an fsync. A writer that cannot persist is poisoned
(ErrWriterPoisoned) rather than silently dropping acknowledged writes.
References. wal.Writer.AwaitDurable; tests
TestServer_AckedCandleIngestIsInWALBeforeAck,
TestWriter_PoisonedAfterPermanentFlushFailure. See
Durability and acknowledgements and
The write-ahead log.
One index handle per stream
Decision. Exactly one StreamIndex instance writes each stream's stream.idx, obtained
from the dispatcher; every component that installs chunks (live flush, history, replication
seed) goes through it.
Context. An index write rewrites the whole file from that instance's in-memory list, and each instance allocates sequence numbers from its own counter.
Reasons. Two writing instances lose each other's entries and collide on chunk file names — this has silently destroyed a back-fill before. Reading through a separate handle is fine; writing is not.
Alternatives refused. Coordinating several writers (locks across instances) instead of having one.
Consequences. New install paths must be wired through the dispatcher's pair.
References. /internal/ingestion/dispatcher.go,
/internal/storage/stream_index.go; tests
TestHistoryBackfill_BelowTheCacheAnchorSurvivesRestart,
TestSeedSink_AHeartbeatMidSeedNeitherHidesNorErasesTheSeededHistory. See
Indexes and the on-disk layout.
Sequence numbers, not positions
Decision. A chunk is addressed by its sequence number (SeqNo), never by its position in
stream.idx; the index header records the highest SeqNo ever issued, and compaction never
lowers it.
Context. Entries are ordered by time, and a back-fill inserts below existing entries, shifting every position. Compaction can drop the highest SeqNo.
Reasons. Positions shift under concurrent compaction (a query planned against positions read the wrong chunk); a counter rebuilt from surviving entries could issue a SeqNo twice, and a copy holding the first would skip the second.
Alternatives refused. Positional addressing; rebuilding the counter from the index.
Consequences. stream.idx is format v5; older formats are refused.
References. /internal/storage/stream_index.go;
tests TestStreamIndex_ASeqNoIsNeverIssuedTwiceAcrossCompactionAndRestart,
TestPlanner_Execute_CompactionBetweenPlanAndExecute. See
On-disk formats.
Fixed-point delta-of-delta is the default codec
Decision. Candle columns are stored as fixed-point integers compressed with bit-packed
delta-of-deltas (fixed_point_dod). Gorilla XOR and raw encodings remain selectable.
Context. Prices have a fixed decimal precision; floats do not compress well with generic methods.
Reasons. Exact fixed-point conversion avoids float rounding; delta-of-delta exploits the smoothness of price series and never expands data. Gorilla, the float-oriented alternative, is kept for values where XOR wins.
Alternatives refused. Gorilla as the default; a fast reciprocal-multiply fixed-point conversion (it was wrong for hundreds of thousands of values and was replaced by one exact conversion).
Consequences. Every value must be within the storable magnitude, checked at ingest. The codec is a cluster setting so copies compress identically; each chunk records its own codec, so changing it never rewrites old chunks.
References. /internal/compression/chunk.go,
/internal/compression/fixed_point.go; tests
TestCompressionRatio_Regression, TestDecodersAgree,
TestFixedPointRoundTripLargeValues. See
Chunks and compression.
No assembly
Decision. Mirexa contains no hand-written assembly. Re-adding any requires, in the same change, a benchmark showing more than 20% end-to-end gain on a real workload and a differential fuzz test against the scalar code.
Context. Assembly once in the codebase was where silent data corruption lived, and much of it was not vectorized at all.
Reasons. Correctness of stored market data outweighs micro-optimization that tests did not cover.
Alternatives refused. Keeping assembly behind tests written from the same mental model.
Consequences. The codec is pure Go.
References. No .s files exist in the repository; test
TestFixedPointRoundTripLargeValues.
Chunks are read, not memory-mapped
Decision. Queries read chunk files with os.ReadFile and plan against a snapshot of the
stream index.
Context. Under many concurrent readers, mmap/munmap take the process's address-space
lock for writing, serializing every query.
Reasons. Measured on one machine on 2026-10-16: with mapping, a node sustained 13–18K reads/s with about 2.4 of 12 cores busy; reading files took it to 61–106K reads/s.[1]
Alternatives refused. Memory-mapping chunk files.
Consequences. Each read copies chunk bytes into the heap; a decoded-chunk cache
(storage.decoded_chunk_cache_bytes, 256 MiB by default) absorbs repeats.
References. /internal/storage/chunk_file.go; tests
TestReplicaSupervisor_APrimaryRepairsWhileServingItsReads,
TestPerfCheck_APrimaryRepairsWhileServing50KReadsPerSecond (runs only with
MIREXA_PERF_CHECK=1). See The read path.
CRC-32C everywhere
Decision. WAL records, checksummed wire payloads, chunk data and footers, and replication transfers all use CRC-32C (Castagnoli).
Context. Every byte that crosses a disk or network boundary needs corruption detection.
Reasons. One polynomial, hardware-accelerated on common CPUs, detects every single-bit error in a chunk. Where a checksum's absence fails open (an epoch prefix, a redirect's epoch), the field is checksummed even though it is small.
Alternatives refused. A second hash (xxHash64) for replica comparison; unchecksummed control payloads where corruption would be accepted.
Consequences. Rot is detected on every chunk read and by the scrubber.
References. /internal/wal/record.go,
/internal/wire/payload.go; tests
TestUnmarshal_RefusesEverySingleBitFlip. See The write-ahead log.
Derived streams are stored
Decision. A stream can declare a lineage — derived from another stream's trades or candles — and its bars are computed by the node serving it and stored like any other stream's. Ad hoc rollups at query time also exist, by the same rules, and are stored nowhere.
Context. Users need 1m bars from trades and 1h or 1d bars from 1m bars.
Reasons. Stored bars are read at the cost of a plain read. Only the node serving the derived stream derives it, so a copy never derives in parallel with its primary. A cycle is unrepresentable because each candle link at least doubles the interval. Lineage is metadata, changed only by its own call, so a calendar update cannot drop it.
Alternatives refused. Computing every derived bar at query time as the primary mechanism.
Consequences. A source correction or fill re-derives down the chain. Ingest with the deriver running cost about 2.7× at a saturating ~5M trades/s on one stream (measured 2026-10-22, one machine).[2]
References. /internal/materialize,
/internal/types/lineage.go; tests
TestLineage_RefusedDeclarations, TestDeriveTicks_ABarIsItsTradesByTimestampTiesByArrival,
TestServedHere_FollowsTheResolver, TestRollup_AnswersWhatAStoredDerivationWould. See
Derived streams and lineage.
Old formats are refused, not upgraded
Decision. When an on-disk or replicated format changes version (stream.idx v5, the
control-plane snapshot v12, wire protocol v2), the older version is refused outright.
Context. A newer reader meeting an older file can misread an absent section as "empty".
Reasons. The failure to avoid is an old header accepted and a missing section read as "no partitions" or "no settings" — silently restoring a cluster that has forgotten its directory. A loud refusal is recoverable; a silent misread is not.
Alternatives refused. In-place upgraders and multi-version readers.
Consequences. A format change requires fresh state for development clusters; there is no interoperability between protocol v1 and v2 clients.
References. snapshotVersion in /internal/cluster/codec.go,
streamIndexVersion in /internal/storage/stream_index.go,
ProtocolVersion in /internal/wire/protocol.go; tests
TestState_AVersionOneSnapshotIsRefused. See On-disk formats.
Protocol and clients
A binary wire protocol of its own
Decision. Clients speak a framed binary TCP protocol (header, flags, CRC-protected payloads). gRPC is used only for the control plane and node-to-node replication.
Context. The data path carries high-rate candle and tick batches and long-lived subscriptions.
Reasons. Fixed-size records and Mirexa's own codecs keep ingest cheap; one codec per artifact. Exposing reads and writes over gRPC too would be a second protocol for the same operations.
Alternatives refused. Client reads and writes as gRPC.
Consequences. Every parser is fuzzed; a conformance suite (conformance/wire-v2.json)
pins the protocol for other-language SDKs.
References. /internal/wire/protocol.go, /proto/mirexa/replication/v1/replication.proto. See Wire protocol.
Retry safety rests on the shed promise
Decision. The only retryable refusal is a shed: Overloaded (and the replay gate's
equivalent) is raised before anything is stored, so a re-send is a first attempt. The SDK
retries sheds for reads and writes; no other error is retried automatically.
Context. Ingest is also idempotent by (stream, timestamp), but that depends on routing a client cannot observe.
Reasons. Reasoning from a promise the server makes ("nothing was stored") is sound; reasoning from idempotency is only as sound as the client's view of where data lives.
Alternatives refused. Retrying any error that "looks transient".
Consequences. A shed carries a retry hint; the SDK waits it out.
References. /internal/wireclient/retry.go,
ErrorCodeOverloaded in /internal/wire/protocol.go; test
TestMockServer_AShedReadIsRetriedLikeAShedWrite. See
Error codes.
Ambiguous writes are never retried blindly
Decision. A write whose connection fails after it was sent returns
wireclient.ErrAmbiguous: its outcome is unknown, and the caller reconciles by reading back
(or by re-sending, which a restatement makes safe). A write refused before a byte was sent
goes out on a fresh connection as a first attempt.
Context. A batch may have been applied with only the acknowledgement lost.
Reasons. A blind retry of an applied batch duplicates or silently re-orders intent; a reconnect loop that conflates "before" and "during" duplicates data.
Alternatives refused. Automatic retry of ambiguous writes; an offline replay queue in the dashboard (the same hazard one layer up).
Consequences. A primary dying with a write on the wire costs exactly that write's certainty; reads retry either way.
References. /internal/wireclient/resilient.go; test
TestResilient_AWriteAfterTheServerClosedAnIdleConnectionIsSentFresh. See
Durability and acknowledgements.
Redirect, never forward
Decision. A node that does not serve a stream answers with a REDIRECT naming the
partition, its epoch and the primary's address. It never proxies the request.
Context. In a cluster each partition has one primary; clients may reach any node.
Reasons. A redirect is emitted after the permission check and before anything is dispatched, so the refusing node provably holds nothing and following it is a first attempt. A forwarder holds the request, so a failure becomes ambiguous where it was clean; it also doubles the hop. The control plane makes the same choice for writes on a follower.
Alternatives refused. Request forwarding by non-owners.
Consequences. Clients must be cluster-aware (the routing client).
References. /internal/network/redirect.go; tests
TestRoutingClient_AFailedDialStillYieldsTheSameNodeClient,
TestRouting_ANodeBehindTheClientIsWaitedOutNotBlamedForALoop. See
Partitions and routing.
A redirect is a frame, not an error
Decision. REDIRECT (0x20) is a frame of its own with typed, checksummed fields, and
trailing bytes are refused.
Context. The error frame carries only a code, a message and a retry hint.
Reasons. An address and epoch inside an error message would mean parsing error text. A redirect is re-targetable, not retryable; as an error it would be retried against the address that just declined it. A corrupted epoch would wedge a client's route cache, so the payload is checksummed.
Alternatives refused. An error code with the address in its message.
Consequences. Each hop must carry a strictly newer epoch, or an older one is waited out as a node not yet caught up; an equal epoch from a different node is a contradiction and fails at once.
References. /internal/wire/protocol.go, /internal/wireclient/redirect.go. See Wire protocol.
The client routes, and refusals correct its cache
Decision. wireclient.RoutingClient takes contact points, keeps a connection per node,
caches each stream's route with its epoch, and follows redirects itself. A route is
invalidated by a refusal carrying a newer epoch, never by a subscription or a timer.
Context. A non-member client holds neither the partition count nor the directory, so it cannot compute where a stream lives.
Reasons. The refusal a stale route produces is exactly the correction it needs, and a client relying on refusals cannot miss one. Every method goes through one interceptor so no request can skip routing.
Alternatives refused. A topology subscription feed; a client-side copy of the directory (it goes stale exactly when a primary dies).
Consequences. The first request to each stream may cost one redirect.
References. /internal/wireclient/routing.go,
/internal/wireclient/routecache.go; test
TestRoutingClient_AColdRequestReachesALiveContactPointPastTheDeadOnes. See
Partitions and routing.
The nodes answer a fan-out's split
Decision. A multi-stream query sent to any node is answered in place for the streams it
serves; each foreign sub-query comes back with status Elsewhere and its redirect. The client
regroups by node and sends one leg per node.
Context. A client cannot plan the split itself (it cannot compute owners).
Reasons. The nodes already know the directory. Results are positional and each comes whole from the one node serving its stream, so nothing needs merging.
Alternatives refused. Executing foreign sub-queries locally (answers "no data" where the truth is "elsewhere"); a client-side k-way merge.
Consequences. Legs are cut at a node's per-request sub-query cap (128 by default).
References. QueryStatusElsewhere in
/internal/wire/multiquery_payload.go,
/internal/wireclient/fanout.go; tests
TestFanOut_TenNodesAnswerAThousandStreamsAsOneNodeHoldingThemAllDoes,
TestFanOut_ABatchOverANodesPerRequestCapIsSentInPieces. See
Reading data.
Partial results are an error, not a knob
Decision. When a node cannot answer, its sub-queries come back unanswered and the call
returns the other nodes' answers with a *PartialResultError naming each failed node.
Context. Fan-out reads and cross-node stream listings can lose a node.
Reasons. An empty series would read as "no data in that range". A tolerance knob turning missing data into a nil error is "silently complete"; the decision belongs to the caller.
Alternatives refused. A configurable failure tolerance that returns nil.
Consequences. Callers must check for PartialResultError explicitly.
References. PartialResultError in /internal/wireclient/fanout.go.
See Go SDK.
Reads go to copies by default
Decision. A routing client spreads candle reads over a stream's primary and its in-sync
copies by default, choosing a member per stream with a sticky hash. A copy refuses past
cluster.copy_read_max_staleness (5s); any refusal falls back to the primary. Callers opt out
with ResilienceOptions.PrimaryReads or WithFreshReads(ctx), and a stream the client just
wrote is read from the primary for 10 seconds.
Context. Copies hold the same bytes as their primary by construction.
Reasons. Spare read capacity on copies; stickiness keeps a stream's newest bar from moving backwards between reads.
Alternatives refused. Primary-only reads as the default (now an opt-out).
Consequences. A read may be up to the staleness bound behind. On one shared machine the throughput gain was within noise (measured 2026-10-23); the gain on separate hardware is unmeasured. Tick reads are never served stale.
References. /internal/wireclient/replicas.go; tests
TestReplicaReads_SpreadStreamsAcrossThePrimaryAndItsCopy,
TestReplicaReads_AStreamIsStickyToOneNode, TestReplicaReads_AnOptOutNeverReachesTheCopy.
See Reads from copies.
Subscriptions deliver closed bars only
Decision. A subscription delivers closed candles; the partials flag is refused
explicitly. Backfill-on-subscribe guarantees no gap between history and live, but may deliver
a bar twice.
Context. The ingest path receives closed bars; it has no in-progress bar to send.
Reasons. Refusing loudly is better than a flag that silently does nothing. Overlapping the backfill window with the live queue is what makes the hand-off gap-free.
Alternatives refused. Inventing partial bars; a hand-off that risks a hole.
Consequences. Consumers dedupe by timestamp. Live batches are numbered from 1 and a dropped batch consumes its number; backfill batches carry 0, outside that numbering.
References. /internal/network/server.go,
/internal/wireclient/subscribe.go; tests
TestServer_BackfillStreamsHistoryBeforeLive,
TestSubscriptionRegistry_DroppedBatchLeavesSequenceGap. See
Subscribing to live data.
Cluster
Raft for the control plane only
Decision. Raft replicates cluster metadata only — the node registry, the partition directory, cluster settings, migrations and revoked keys. Candle and tick data never enter the Raft log.
Context. Mirexa needs agreement on which node is primary of what; it also needs a fast ingest path.
Reasons. Consensus is priced for decisions, not a firehose: a quorum commit per batch adds a round trip and a second fsync to sub-millisecond acks; it writes the same bytes durably twice (consensus log, then WAL and chunks); and its total order is a property candle ingest already has by being idempotent by (stream, timestamp).
Alternatives refused. Replicating partitions through per-partition Raft groups; majority vote over Merkle trees to settle divergence.
Consequences. A partition has one primary and copies, with no term, quorum or election; fencing is done by epochs and leases instead. With asynchronous copies, a primary that crashes can lose writes it acknowledged after its copies' last pull (see Known limitations). Serving as a primary requires the control plane's acknowledgement (see A lease before automatic failover).
References. /internal/raft/control_fsm.go; test
TestDegradedMode_TheDataPlaneSurvivesLosingControlPlaneQuorum (data never flows through
the control plane). See Cluster architecture.
hashicorp/raft, with its own log store
Decision. Consensus is github.com/hashicorp/raft v1.8.0 with its BoltDB log store
under <data_dir>/raft/. Only internal/raft imports it.
Context. A previous consensus library pulled in an embedded key-value store and dozens of modules.
Reasons. A tagged release, duration-based configuration, a single group (right for control-plane-only), and a far smaller dependency tree. Containing the import in one package made swapping libraries a one-package change.
Alternatives refused. A custom Raft log store over Mirexa's own WAL (a second durability implementation); a separate cluster data-dir knob (the log must not outlive its state).
Consequences. There is no read index: a linearizable read is a Barrier (which appends a
log entry) plus a local read, so routing and status reads use local state.
FSM.Apply cannot return an error; a node that cannot apply an entry is reported through an
observer and an ERROR log. The library offers no in-place voter demotion.
References. /internal/raft/node.go,
/go.mod; tests TestRaftNode_LogStorageIsCreatedUnderTheDataDir,
TestRaftCluster_DemotingAVoterInPlaceIsASilentNoOp. See
The control plane.
The stream catalog is not replicated
Decision. Raft does not hold a list of streams. A stream's existence is derived:
hash(stream) → partition → primary, and the primary either has it or does not.
Context. Stream metadata (calendar, lineage, cache size) lives with the stream on its partition and travels to copies with the seed.
Reasons. A replicated list of names is a second source of truth, and a second open handle on the registry file had already been shipped by accident.
Alternatives refused. A replicated stream catalog.
Consequences. Listing every stream in a cluster is a fan-out to all nodes
(ListAllStreams), a costly query a caller chooses.
References. /internal/raft/control_fsm.go, /internal/types/stream.go. See The control plane.
Hash modulo a fixed partition count
Decision. A stream's partition is FNV-1a(symbol, exchange) mod partition_count
(4,096 by default). The timeframe is not part of the key, so every timeframe of a symbol
shares a partition. Partitions are moved between nodes by the directory.
Context. Streams must map to partitions stably across builds and nodes.
Reasons. Consistent hashing exists to limit remapping when the bucket count changes; here it never changes. Movability is provided one level down by the partition directory (Kafka's model). Colocation keeps a symbol's derived streams on the node deriving them.
Alternatives refused. Consistent hashing; routing metrics (routing is a pure function).
Consequences. The partition count is immutable; golden values pin the hash across builds.
References. AssignPartition and PartitionKey in
/internal/types/stream.go; tests
TestAssignPartition_DistributionIsUniform, TestAssignPartition_IsStableAcrossBuilds. See
Partitions and routing.
Few cluster settings, and immutable ones
Decision. Only values whose disagreement produces a wrong answer neither node can detect are cluster settings: partition count, compression codec, liveness timeout and replication factor. Partition count, liveness timeout and replication factor are immutable once agreed; updates are compare-and-set. A node reads them from its own applied state.
Context. Most configuration (WAL shards, buffer sizes) legitimately differs per machine.
Reasons. Changing the partition count remaps every stream. Changing the liveness timeout could fence a primary under a lease it still holds. Changing the factor needs a policy for which copy to drop, which does not exist. Compare-and-set makes bootstrap safe: every founding node proposes at version 0 and exactly one wins.
Alternatives refused. Replicating security.tls_enabled (a fleet-wide downgrade channel
a node cannot honour without rebinding); hot reload of cluster settings (nothing a running
node could change); fetching settings over RPC.
Consequences. Consensus starts before storage. cluster.strict_settings is off by default:
a node that cannot agree in settings_timeout starts on its own YAML, loudly.
References. /internal/cluster/settings.go; tests
TestSettings_PartitionCountIsImmutableOnceAgreed,
TestSettings_LivenessTimeoutIsAgreedOnceAndNeverChanges,
TestSettings_ReplicationFactorIsValidatedAndImmutable,
TestServerBinary_ARestartedLeaderFencesOnTheAgreedLivenessTimeout. See
The control plane.
The epoch is a log index
Decision. A partition's epoch is the Raft log index of the entry that installed its
current primary. It advances only when the primary changes. Writes carry the epoch their
sender believed (FlagEpoch), and the primary checks it.
Context. A fencing token must be monotonic and never reused, including across a control-plane leader change.
Reasons. Only Apply knows the index, so a proposer cannot assign (and reuse) one. Moving
the epoch when only a secondary changed would refuse writes from a node still serving.
Alternatives refused. A counter assigned at proposal time; distinct epochs per partition during bootstrap (one entry places the whole keyspace).
Consequences. The epoch check stops stale clients, not a stale server; a partitioned primary is bounded by the lease instead.
References. /internal/cluster/partition.go,
/internal/network/fencing.go; tests
TestState_TheEpochIsMonotonicAcrossAControlPlaneLeaderChange,
TestState_TheEpochDoesNotMoveWhenThePrimaryDoesNot. See
Partitions and routing.
Heartbeats stay out of the log
Decision. Node heartbeats go to the control-plane leader and live in its memory
(cluster.Liveness). Only the transitions they justify — a fence, a registration — are Raft
entries. A registration's incarnation is the log index that created it, and a fence must name
it.
Context. Every node beats every third of the liveness timeout.
Reasons. One log entry per node per interval is the firehose objection again (Kafka's controller model). A new leader starts every clock at its election, so it never fences the whole cluster for silence it did not observe. Incarnation matching stops a fence proposed for a node that has since restarted.
Alternatives refused. Replicated heartbeats; timestamps as incarnations.
Consequences. Liveness evidence is lost on leadership change by design. A leader still verifies its quorum on each heartbeat, without appending.
References. /internal/cluster/liveness.go; tests
TestLiveness_ANewLeaderDoesNotFenceTheWholeCluster,
TestState_FenceRefusesAStaleIncarnation,
TestFenceLoop_ASilentNodeIsFencedWithinItsTimeoutAndNoSooner. See
Failure detection, leases and failover.
Seeds are contact points
Decision. cluster.seeds lists control addresses used for first contact only. Any
member says who leads. Afterwards a node tries the members its own state knows, leader first,
then its seeds. A bootstrapping node seeds itself and registers through the same call.
Context. Registration is a write only the leader accepts, and the leader's address is in the registry that registration fills.
Reasons. A config list breaks the circle without naming a leader that will move. Cassandra seeds, Kafka bootstrap servers and Consul's retry-join work the same way.
Alternatives refused. Naming the leader in config; walking the seeds on every request (a node whose seeds had all left stopped serving).
Consequences. ControlAddr is carried in the registry, because nothing else can derive it.
References. /internal/control/join.go; test
TestJoiner_AMemberWhoseSeedsHaveAllLeftStillReachesTheCluster. See
Joining, draining and decommissioning nodes.
Every node joins as a non-voter
Decision. All nodes run the same binary. A joining node is admitted to the Raft group as a
non-voter before it builds anything; the leader promotes toward cluster.voters (3; odd,
1–7), lowest id first, only nodes whose log is caught up, never to an even count. Voter
membership changes on failure or departure, never to rebalance.
Context. The control plane needs 3 or 5 voters regardless of cluster size.
Reasons. A new member as a voter raises quorum before it holds any log. Self-promotion by several nodes at once is a configuration race. The library has no in-place demotion, so voters are not shuffled. Consul's autopilot does this on the same library.
Alternatives refused. Operator-assigned roles or a separate controller binary; self-promotion.
Consequences. A decommissioned leader hands leadership away before it is removed.
References. /internal/control/promotion.go; tests
TestRaftCluster_NonVotingReplicaIsNotCountedInQuorum,
TestPromotionSweep_ADecommissionedLeaderHandsLeadershipAwayFirst. See
Joining, draining and decommissioning nodes.
Pull replication in the engine's own encodings
Decision. A copy dials its primary (ReplicationService.Seed for flushed artifacts,
Tail for WAL records after a watermark). Payloads are Mirexa's on-disk encodings — chunk
files, index entries, gap ranges, WAL records — inside bytes fields.
Context. A copy must end up holding exactly its primary's flushed state.
Reasons. Pull puts the cursor with the party that must survive losing it; a restarted primary holds no per-follower state (Kafka's follower fetch). Shipping verbatim bytes makes a copy byte-identical by construction, which is what makes byte comparison, repair and promotion simple.
Alternatives refused. Push pipelines; re-ingesting records on the copy; a separate replication serialization.
Consequences. A copy has no live writer of its own; tail records go to a per-partition replica log replayed at promotion. Golden bytes pin every message.
References. /proto/mirexa/replication/v1/replication.proto;
tests TestGolden_EveryMessagePinsItsWireBytes, TestCatchup_ADeadPrimaryKeepsItsCopiesInSync.
See Replication.
A separate mTLS listener between nodes
Decision. Replication runs on its own listener (cluster.replication_addr) with
mandatory mutual TLS 1.3. A node's identity is its certificate (CN=mirexa-node-<id>),
issued by an offline CA (mirexa-cli certs).
Context. The control plane authenticates operators with bearer tokens; replication must know which node is asking.
Reasons. Per-node identity is exactly the property used here. A separate listener keeps node traffic out of the operator surface, whose interceptors were unary-only.
Alternatives refused. Sharing the control listener; an authorization interceptor (the question is per-partition and lives in the request); rate limiting replication (it throttles the catch-up that decides whether a cutover is safe).
Consequences. Certificate rotation is restart-free (SIGHUP); trusting a new CA needs a restart. Key files must be mode 0600.
References. /internal/replication/tls.go,
/internal/nodecert/nodecert.go; test
TestCA_AGrandchildCertificateNeverVerifies. See TLS and certificates.
A lease before automatic failover
Decision. A primary serves only while it holds a lease: an acknowledged heartbeat grants
three quarters of the liveness timeout, counted from the heartbeat's send time. Without a
lease it refuses reads and writes with PartitionUnavailable. Failover waits one liveness
timeout after the leader first sees a fence.
Context. Without a lease the cluster cannot tell a crashed primary from a partitioned one that keeps accepting writes.
Reasons. The lease ends a quarter of a timeout before the earliest fence, and the failover delay outlasts any lease the fenced node can hold, so two primaries never serve at once. There is deliberately no autonomous mode: a node that cannot be vouched for cannot rule out having been replaced.
Alternatives refused. Promoting copies without a lease; operator-declared failover only; keeping a clustered node serving without its control plane.
Consequences. Losing the control plane stops every primary within its lease. A failover takes about two liveness timeouts end to end. Measured 2026-10-08 at T=3s: a cut-off primary refused 1.71–1.77s after the cut and was fenced 3.45–3.49s after.[3] A process paused past the lease margin after checking it can still write (every lease's caveat).
References. /internal/cluster/lease.go; tests
TestLeaseDuration_EndsBeforeTheEarliestFence,
TestFailoverDelay_OutlastsAnyLeaseAFencedNodeCanHold,
TestLease_APrimaryCutOffFromTheControlPlaneStopsBeforeItCanBeFenced,
TestServerBinary_APrimaryStopsServingWhenItsControlPlaneIsGone. See
Failure detection, leases and failover.
Failover on by default, automatic rebalancing off
Decision. Automatic failover of a dead primary's partitions to in-sync copies has no off
switch. The rebalancer always plans (every cluster.rebalance_interval), but executes its
plan only when cluster.rebalance_auto is true (default false); otherwise an operator applies
it with MigratePartition.
Context. Failover acts only on partitions nobody is serving; rebalancing moves data between healthy nodes.
Reasons. Failover moves no data and restores availability; its trade-off is the async-ack loss window, which exists either way. Rebalancing moves data at a time the operator may not want, and the decision to let a cluster do so unasked should be explicit.
Alternatives refused. A failover off switch; executing rebalance plans by default; event-triggered rebalancing (events are when the picture is least settled).
Consequences. Turning rebalance_auto on logs a startup warning; the plan and its gauges
are visible either way.
References. /internal/control,
/internal/config/config.go; tests
TestServerBinary_ADeadPrimaryIsFailedOverToItsCopy,
TestPlanFailover_SpreadsADeadNodesPartitionsOverItsSurvivors. See
Moving partitions and rebalancing.
In-sync is earned continuously
Decision. A copy joins its partition's in-sync set when it is level with the primary's
durable watermark, and leaves it after InSyncStaleAfter (2 × liveness timeout + 2s) without
being level — but only while the registry still believes the primary.
Context. Failover promotes only in-sync copies.
Reasons. A copy whose replication broke while its node stayed healthy (blocked port, expired certificate) must not be promoted over everything it missed. When the primary itself dies, every copy stops being level at once; leaving then would remove every failover candidate exactly when one is needed.
Alternatives refused. In-sync as "was level once this epoch"; dating "level" by the instant of a check (evicts healthy copies of busy partitions).
Consequences. The in-sync window bounds what a promoted copy can miss.
References. InSyncStaleAfter in /internal/cluster/lease.go;
tests TestInSyncStaleAfter_OutlastsTheFenceOfADeadPrimary,
TestCatchup_ADeadPrimaryKeepsItsCopiesInSync. See Replication.
A graceful cutover rolls back only before its commit point
Decision. Moving a primary drains the old primary (writes quiesced under in-flight tokens), finishes the copy's catch-up, verifies coverage, then proposes one directory entry. Before the proposal everything rolls back by reopening writes; after it, only a definite refusal thaws, and anything ambiguous leaves the partition drained. A committed flip never reopens the old primary.
Context. The goal is that a graceful move loses no acknowledged write.
Reasons. Reopening the old primary under a flip that did commit would let it acknowledge writes the directory has moved away from. Promotion is convergent (it is retriggered by observed state), so a crash between flip and replay still completes.
Alternatives refused. Symmetric rollback; pre-copy convergence before the freeze (not built — see Known limitations).
Consequences. Under heavy load the partition takes no writes while the copy catches up.
References. /internal/replication,
/internal/network/fencing.go; tests
TestCutover_UnderConcurrentWritesNoAckedWriteIsLost,
TestCutover_TheOldPrimaryAcksNoWriteBeforeItHasAppliedTheFlip,
TestDrainer_FlushesOnlyThePartitionItFreezes. See
Moving partitions and rebalancing.
Copies are moved, never dropped
Decision. Emptying a node (a drain) moves each copy it holds as add → catch up → remove, recorded as a typed replica-move intent, so a partition's copy count never drops below where it started. Primaries leave a draining node before its copies do.
Context. A copy exists because an operator, an aborted migration or the replication factor asked for it.
Reasons. Dropping a copy to empty a node silently halves that partition's redundancy.
Alternatives refused. Removing copies from a leaving node directly.
Consequences. A drain takes as long as its moves; measured 2026-10-09 at production cadences, 500 partitions took about 25 minutes, almost all waiting on loop intervals.[4]
References. StartReplicaMove in /internal/cluster/migration.go;
test TestReplicaMove_KeepsTheCopyCountAtEveryStep. See
Joining, draining and decommissioning nodes.
The replication factor only adds
Decision. cluster.replication_factor (default 1, range 1–7) is enforced by a leader loop
that adds copies onto online nodes holding none of the partition's roles. It never removes a
copy. A divergent copy and a copy on an offline node count as present.
Context. Copies already existed before the factor; the factor automates adding them.
Reasons. Adding is safe; removing needs a policy for which copy to drop, which does not exist — which is also why the factor is immutable. Counting an offline node's copies avoids re-replicating during a transient outage.
Alternatives refused. Surplus-copy removal; replacing copies of a node that stays offline automatically.
Consequences. A dead node's copies are moved by draining it, not replaced.
mirexa_cluster_copies_missing shows the shortfall.
References. PlanReplication in /internal/cluster/replication.go,
/internal/control/replication.go; tests
TestServerBinary_TheReplicationFactorGivesEveryPartitionItsCopies. See
Replication.
Balance by bytes and write rate, never onto a copy
Decision. The rebalance planner balances primaries by the bytes a node can move (what it is primary of) and by live write rate, moving the partition nearest half the gap and never at or above it. It never migrates onto a node that holds a copy; it reaches such a node with a swap, cutting the in-sync copy over to primary and keeping the old primary as a copy.
Context. Partition count is an even spread of very uneven things.
Reasons. Counting secondary copies or lingering files would move a real partition to compensate for load nothing can move. A partition at or above the gap relocates the hotspot. Migrating onto a copy consumes it (one copy fewer); a swap moves nothing. Bytes alone left one node taking most writes. An in-flight move counts at its target so successive plans do not empty a node.
Alternatives refused. CPU, memory and free disk as balance inputs (symptoms; nothing measures capacity); round-robin placement.
Consequences. The planner answers "cannot tell" (rendered as NaN) until it has load reports from every online node and rates over half its window.
References. /internal/cluster/rebalance.go; tests
TestPlanRebalance_CountsOnlyWhatItCanMOVE,
TestPlanRebalance_NeverMovesAPartitionOntoACopyOfItself,
TestPlanRebalance_SwapsOntoAnInSyncCopy. See
Moving partitions and rebalancing.
Divergent copies are quarantined, never deleted
Decision. When a copy holds another history than its primary (failed over around it, or
files from an earlier role), its partition directory is moved under
quarantine/partition_<id>-epoch_<e>[-diverged|-released|-corrupt] with one durable rename,
and the node re-seeds from nothing. Nothing in Mirexa deletes a quarantine.
Context. Failover marks every copy it did not promote as divergent; a node may also return holding files of a partition it no longer has a role in.
Reasons. Seeding on top of another history splices two histories. The quarantine is evidence of everything the node held; deleting data because a local view says someone else owns it is the most dangerous operation a cluster can automate.
Alternatives refused. Deleting divergent data; reconciling by majority vote.
Consequences. Quarantines consume disk until an operator removes them.
References. /internal/storage/layout.go; tests
TestLayout_QuarantinePartitionMovesEverythingAndDeletesNothing,
TestReplicaSupervisor_ADivergentCopyIsQuarantinedAndNothingOfItIsDeleted,
TestReplicaSupervisor_ACopyHoldingAnotherHistoryIsMovedAsideAndSeedsAgain,
TestDivergentCopy_ReturnsAsAnInSyncCopyOfTheNewPrimary. See
Reconciliation, scrubbing and repair.
Copies mirror their primary's retention
Decision. A copy retires chunks its primary's retention dropped, automatically — but only entries that end before the primary's oldest retained base, and only after the seed's divergence check has accepted the primary's history.
Context. Retention runs inside a live writer, which copies do not have.
Reasons. Otherwise a copy keeps everything its primary retired and, once promoted, serves it. The two guards stop a primary that lost its index from taking every copy's data with it.
Alternatives refused. Copies never deleting; mirroring any absent entry.
Consequences. mirexa_reconcile_retired_chunks_total counts retirements.
References. /cmd/server; tests
TestReplica_ACopyDropsWhatItsPrimarysRetentionDropped,
TestSeedSink_NothingIsMirroredFromAPrimaryWithAnotherHistory. See
Reconciliation, scrubbing and repair.
Scrub at a rate, repair from a peer
Decision. Every node re-reads the candle chunks of partitions it holds at
cluster.scrub_bytes_per_second (8 MiB/s; 0 off), and a chunk that fails verification is
repaired from a peer: a primary from a copy, a copy only from its primary
(FetchArtifact), and only with bytes that verify against the requester's own entry.
Context. Rot is found only where something reads it; a seed never re-reads below a copy's floor.
Reasons. A rate, not a schedule, because the cost is reads competing with ingest and queries. Restricting who may answer whom stops a copy from receiving a version of a chunk it was never sent.
Alternatives refused. Merkle trees and majority vote; a repair queue; a separate repair throttle.
Consequences. At the default rate, 100 GB takes about 3.3 hours per cycle (arithmetic, not measured). Tick chunks are not scrubbed.
References. /cmd/server/scrub.go,
/cmd/server/replica.go; tests
TestChunkScrubber_FindsEveryInjectedRotWithinOneFullCycle,
TestReplicaSupervisor_APrimarysRottenChunkIsRepairedFromItsCopy,
TestReplicaSupervisor_ACopysRottenChunkIsRepairedFromItsPrimary. See
Reconciliation, scrubbing and repair.
A failed consensus start is fatal
Decision. With cluster.enabled, a node that cannot start Raft, or cannot be admitted
within cluster.join_timeout, exits. initial_members empty means join; non-empty means
bootstrap.
Context. A node configured to replicate that silently runs standalone accepts and acknowledges writes the cluster does not hold.
Reasons. That is the worst available outcome; failing to start is recoverable.
Alternatives refused. Degrading to standalone.
Consequences. Passing a member list to a joining node forms a second one-member cluster — a configuration error the docs call out.
References. /cmd/server. See Operating a cluster.
Security
Offline Ed25519 tokens
Decision. Client sessions are authenticated by Ed25519-signed tokens minted offline by
mirexa-cli token; nodes verify them against trusted public keys in config. There is no token
service. A session renews its token over its open connection (REAUTH); expiry is enforced
mid-session.
Context. Authentication should add no network dependency or online secret.
Reasons. Offline signing keeps the signing key off every server. Ed25519 is fast, deterministic and has small keys. A writer is refused on its next frame after expiry; a subscriber, which sends nothing, is cut by a timer.
Alternatives refused. A control-plane token issuer (an online signing key on every voter); JWT (algorithm agility lets a verifier honour attacker-supplied instructions).
Consequences. Tokens are bounded at one hour (wire.MaxTokenValidity), so long-running
clients use a TokenSource that re-reads a token file.
References. /internal/auth,
/cmd/cli/token.go; tests TestAuth_SDKPresentsACLIIssuedToken,
TestReauth_* in /tests/auth_renewal_test.go. See
Authentication and tokens.
Authentication on by default
Decision. security.auth.enabled defaults to true (decided by the project owner,
2026-10-31; it defaulted to false before). A single node with no security.auth.trusted_keys
generates its own Ed25519 issuer under <data_dir>/auth/, trusts it, and keeps an admin token
carrying every permission in <data_dir>/auth/admin.token, re-minted while it runs. A clustered
node with no trusted keys is refused at config load. security.max_permissions clamps every
grant whether or not authentication is on.
Context. An authentication-enabled node refuses every client without a token, and a node needs a trusted key to verify one. That was the reason auth defaulted to off: a first start would otherwise have needed key material before anything worked. With it off, an unconfigured node exposed on a network accepted reads and writes from anyone who could reach its port.
Reasons. A generated issuer keeps a first start usable with no setup — the client reads
one file — while nothing is served unauthenticated. The key is an ordinary
mirexa-cli token keygen key, so narrower tokens are minted from it with the usual tool, and
it is reused across restarts, so tokens outlive one. A cluster is refused rather than
provisioned because each node would generate a different issuer and a token from one would be
refused by the node it is redirected to — a failure that would look like a bad token rather
than a configuration.
Alternatives refused. Keeping auth off by default (an unconfigured node trusts every client). Auth on with no keys refused at startup (every first start needs setup). A generated issuer in a cluster (each node trusts a different key).
Consequences. A client without a token is refused by a node on defaults, including every
client written against the old default. A private signing key lives on the node; an operator
who wants it elsewhere configures trusted_keys, which turns the generated issuer off. A
cluster must be given its keys (see
Known limitations).
security.auth.enabled: false restores the old posture. control.admin_auth is a separate
switch and still defaults to off.
References. /internal/config/config.go,
/cmd/server/local_issuer.go, authConflicts in
/internal/config/validate.go; tests
TestServerBinary_ANodeWithNoAuthConfigIssuesItsOwnAdminToken in
/tests/server_binary_default_auth_test.go,
TestLocalIssuer_* in /cmd/server/local_issuer_test.go,
TestAuthConfig_EnabledWithNoKeysLoadsOnASingleNode and
TestAuthConfig_EnabledWithNoKeysIsRefusedInACluster in
/internal/config/auth_validate_test.go. See
Authentication and tokens.
Bearer tokens on the control plane
Decision. The gRPC control plane authenticates with the same Ed25519 tokens carrying the
ADMIN_CLUSTER permission (control.admin_auth). The control listener may bind a routable
address only when admin authentication is on.
Context. The control API can fence nodes and move partitions.
Reasons. The control plane has one privilege level, so per-identity mTLS certificates buy a property then discarded, at the cost of a CA and per-node issuance. Exposure and authentication are one decision: of the four combinations, only "routable without auth" is a disaster, and it is now unrepresentable. Expiry is checked after the signature (it is attacker-supplied until then).
Alternatives refused. mTLS for operators; a loopback-only control plane forever.
Consequences. Enabling admin auth with no trusted keys fails at startup rather than refusing every call.
References. /internal/control/server.go. See Control-plane gRPC API.
Revocation of issuer keys only
Decision. Individual tokens cannot be revoked. An operator can revoke an issuer key
through the control plane (RevokeKey); each node applies the revoked set within about one
sync interval, refuses that key's handshakes and renewals, and cuts its sessions.
Context. Tokens are short-lived and verified offline.
Reasons. Per-token revocation needs online state on every verification. Issuer-key revocation covers a leaked signing key, the case that matters.
Alternatives refused. Token revocation lists; a token service.
Consequences. A leaked token stays valid until it expires (at most an hour).
References. /internal/cluster; tests
TestState_ARevokedKeyStaysRevoked, TestRevokedKeys_SurviveASnapshotRoundTrip. See
Authentication and tokens.
No certificate revocation lists between nodes
Decision. Node certificates have no CRL or OCSP. A compromised node is fenced through the registry; certificates last 90 days; a leaked CA key means replacing the CA.
Context. Node identity is mTLS.
Reasons. A revocation list needs a distribution channel more available than the certificates it revokes. The registry fence is quorum-backed and stops routing at once (etcd, Kafka and CockroachDB ship no CRL checking either).
Alternatives refused. CRL/OCSP.
Consequences. Containment relies on chain verification refusing non-CA intermediates.
References. /internal/nodecert/nodecert.go; test
TestCA_AGrandchildCertificateNeverVerifies. See
mirexa-cli certs.
Subscriber grace defaults to zero
Decision. security.auth.subscriber_grace lets an established subscription keep
receiving for a while past its token's expiry. It defaults to 0.
Context. An orchestrator rewriting a token file and an expiry cut can coincide.
Reasons. It moves one deadline and grants nothing — an expired handshake is still refused, a writer's next frame still refused — but trading a security property for an operational one should be a choice, not an inherited default.
Alternatives refused. A non-zero default.
Consequences. Use token renewal (TokenSource) to avoid expiry cuts.
References. /internal/network; tests
TestSubscriberGrace_ZeroIsTheDefault, TestSubscriberGrace_DoesNotAdmitAnExpiredToken. See
Authentication and tokens.
Dashboard and deployment
Server-Sent Events, not WebSocket
Decision. The dashboard's live feed is Server-Sent Events, consumed in the browser by a
fetch-based client, not the native EventSource. The event id is the last candle's
timestamp, and resumption starts the nanosecond after it.
Context. Data flows one way, server to browser.
Reasons. SSE is plain net/http rather than a WebSocket implementation to write and fuzz,
and its replay id maps directly onto how Mirexa resumes a subscription. Native EventSource
cannot send an Authorization header (it would mean authenticating from the refresh cookie)
and retries forever, including on 401.
Alternatives refused. WebSocket; native EventSource.
Consequences. A window holding no data resumes from the window start, not from zero.
References. /internal/dashboard/stream.go; test
TestDashboard_ChartHandoffFromHistoryToLive. See The web dashboard.
Access token in memory, refresh token in a cookie
Decision. The dashboard's access token lives only in JavaScript memory. Reloads are
survived by a separate refresh credential in an HttpOnly, SameSite=Strict cookie
(__Host--prefixed on HTTPS deployments) that carries no permissions and does not slide. Session tokens are Mirexa's own MAC'd
format (mdash1), not JWT.
Context. A dashboard session can write candles into gaps.
Reasons. Anything in localStorage is readable by any script that ever runs on the page.
The cookie is a refresh credential only, so ambient authority never touches data requests and
the CSRF surface is one endpoint whose response an attacker's origin cannot read. A distinct
prefix and MAC domain stop a refresh token being used as a session token.
Alternatives refused. Tokens in localStorage; a longer-lived session token in the cookie
(an authentication bypass); a sliding refresh window.
Consequences. "Remember me" remembers only the username. Tabs do not share a session.
References. /internal/dashboard/refresh.go,
/internal/dashboard/session.go; test
TestRefreshToken_MACDomainsAreDistinct. See The web dashboard.
No optimistic updates, no toasts
Decision. The dashboard never shows a gap as closed before the node confirms the fill, keeps no offline write queue, and shows errors next to what caused them rather than as transient toasts.
Context. Fills are writes whose outcome may be unknown after a disconnect.
Reasons. Showing a gap closed early, or replaying a write of unknown outcome, invert the node's own rules one layer up where nobody would look. An error with a location (a rejected fill row) belongs beside its form.
Alternatives refused. Optimistic UI and an offline queue; a toast system.
Consequences. Fills feel slower; they are never misreported.
References. /web/src/pages/stream-gaps-optimism.test.tsx. See The web dashboard.
Key-set pagination
Decision. LIST_STREAMS and LIST_GAPS page by an opaque cursor meaning "everything after
this". The dashboard shows Next/Previous, never page numbers, and resets paging on any filter
or sort change.
Context. Streams are created while someone pages.
Reasons. An offset silently skips or repeats entries as the set changes; there is no stable total to number pages from.
Alternatives refused. Offset pagination.
Consequences. A deep link has no "previous" history.
References. /internal/wire/list_gaps.go; tests
TestServer_ListStreamsFiltersBeforePaging, TestServer_ListGapsFiltersBeforePaging. See
Wire protocol.
A reverse proxy serves the SPA
Decision. nginx serves the built frontend and proxies /api to the dashboard; the
dashboard process is an API with no static handler, published on no port. nginx resolves its
upstream through a resolver and a variable rather than once at startup.
Context. The refresh cookie is __Host- and SameSite=Strict.
Reasons. A split-origin deployment loses that cookie silently; one origin keeps it.
nginx otherwise caches an upstream's address forever and black-holes requests when the
container is replaced. Every response carries a default-src 'none' CSP, correct because the
API process serves no HTML.
Alternatives refused. Server-side rendering (adds a Node runtime for no credential it hides); a static handler inside the dashboard.
Consequences. Only the proxy has a ports: entry.
References. /deploy/nginx.conf; tests
TestSecurityHeaders_OnEveryResponse, TestSecurityHeaders_HSTSOnlyWhenTheDeploymentIsHTTPS.
See Deploying with Docker Compose.
Compose, not Kubernetes
Decision. The shipped deployment is Docker Compose. There are no Kubernetes manifests or deployment scripts.
Context. A single-node engine with a local data directory.
Reasons. Manifests for one node are a StatefulSet of one — inventing a cluster topology the deployment does not have.
Alternatives refused. Kubernetes manifests, Helm charts.
Consequences. Clustered deployments are assembled by the operator.
References. /deploy/docker-compose.yml. See Deploying with Docker Compose.
Dashboard-to-node TLS is supported, not forced
Decision. upstream_tls works and fails loudly if the node will not negotiate, but there
is no knob that makes it mandatory.
Context. In every shipped deployment that hop is loopback or a private container network.
Reasons. Refusing to start without TLS would break all of them.
Alternatives refused. A required-TLS knob.
Consequences. Where the hop crosses a boundary, the operator must enable it; the dashboard warns at startup.
References. /cmd/dashboard. See TLS and certificates.
Observability and engineering
Report levels; consumers compute rates
Decision. Nodes report counters and levels (load reports, NODE_STATS, Prometheus
metrics). Rates and percentiles are computed by the consumer from two samples on the
reporting node's clock.
Context. A single sample cannot be a rate.
Reasons. A node computing its own rate needs history and would disagree with the aggregator during exactly the incident the number exists for. The dashboard measures only what the server cannot see (refused handshakes, reconnects).
Alternatives refused. Rates computed on the node; the dashboard re-deriving ingest rates from polls.
Consequences. Rates are null across a restart or a falling counter.
References. /internal/cluster/load.go,
/internal/observability/metrics.go; test
TestCatalog_IsCurrent. See Monitoring and alerting.
Unknown reads as NaN, never zero
Decision. Gauges that cannot be computed (a rebalance plan without complete load reports, partition health on a node that cannot read its state) read NaN.
Context. Zero is a meaningful value ("nothing to move", "nothing down").
Reasons. An all-clear zero when the truth is "unknown" hides an outage.
Alternatives refused. Defaulting to zero.
Consequences. Alert rules must handle NaN explicitly.
References. /internal/observability/metrics.go, /internal/control/health.go. See Metrics.
The cluster planes stop before the data path
Decision. On shutdown a node fails readiness, hands off (sheds new writes, finishes those
in flight, and lets every copy tailing it pull what it made durable, bounded by
network.shutdown_timeout), stops checkpointing, stops the cluster planes, and only then
stops the data path and drains its hot caches to chunks.
Context. A SIGTERMed primary under load used to lose its last seconds of acknowledged writes to failover.
Reasons. Copies must have everything acknowledged before the node leaves; the data path keeps serving while that happens.
Alternatives refused. Stopping the data path first.
Consequences. A clean stop can be slow (see Known limitations). A crash still loses the async window.
References. Server.Handoff in /internal/network/fencing.go;
tests TestShutdown_TheClusterPlanesStopWhileTheDataPathStillServes,
TestServerBinary_ASigtermedPrimaryUnderLoadLosesNoAckedWrite. See
Startup, shutdown and recovery.
Gates instead of coverage thresholds
Decision. Mirexa enforces no coverage percentage. It enforces gates that catch what tests
and linters miss: a reachability check from every main (make reachcheck), a test that every
rename is followed by a directory fsync, a test that every config knob is read, fuzzing of
every parser (make fuzz-short), and tests that every control RPC and dashboard route is
exercised.
Context. A high coverage figure, a clean go vet and a green -race once held alongside
data races and silent corruption.
Reasons. Coverage measures lines executed, not behaviour challenged; chasing it re-adopts the metric that certified the bugs.
Alternatives refused. 80% backend / 70% frontend coverage floors.
Consequences. New parsers need fuzz targets; new knobs and routes need tests to compile past the gates.
References. /cmd/reachcheck; tests
TestDurability_EveryRenameIsFollowedByADirectorySync, TestConfig_EveryKnobIsRead,
TestClusterAPI_EveryRPCIsExercisedByATest, TestDashboard_EveryRouteIsExercisedByATest,
TestControlPlaneFSM_EveryClusterSentinelIsDecided.
References
Source
- /internal/raft/control_fsm.go, /internal/raft/node.go — the control-plane state machine and consensus wrapper.
- /internal/cluster/settings.go, /internal/cluster/lease.go, /internal/cluster/partition.go, /internal/cluster/rebalance.go, /internal/cluster/replication.go, /internal/cluster/migration.go — cluster rules.
- /internal/types/stream.go, /internal/types/gap.go — partition key and fillability.
- /internal/ingestion/dispatcher.go, /internal/storage/chunk_persister.go, /internal/storage/chunk_file.go — write and read paths.
- /internal/wireclient/fanout.go, /internal/wireclient/replicas.go — client routing.
- /proto/mirexa/replication/v1/replication.proto — the replication service.
- /internal/dashboard/refresh.go, /deploy/nginx.conf — dashboard and deployment.
Tests
Each decision above names its tests. All were confirmed to exist at the verified commit.
Further reading
External
- Diego Ongaro and John Ousterhout, "In Search of an Understandable Consensus Algorithm", USENIX ATC 2014 — see Bibliography.
- Cary G. Gray and David R. Cheriton, "Leases", SOSP 1989 — see Bibliography.
- Tuomas Pelkonen et al., "Gorilla", PVLDB 2015 — see Bibliography.
Measured 2026-10-16 on a 12-core development laptop by
TestPerfCheck_APrimaryRepairsWhileServing50KReadsPerSecondand its predecessor runs, recorded in the repository's internal notes;cmd/server/reconcile_measure_test.go. ↩︎Measured 2026-10-22 on a development laptop, recorded in the repository's internal notes; not re-run for this page. ↩︎
Measured 2026-10-08 with a 3s liveness timeout, three runs, by
TestLease_APrimaryCutOffFromTheControlPlaneStopsBeforeItCanBeFenced(cmd/server/lease_test.go). ↩︎Measured 2026-10-09 by
BenchmarkDrain_AtProductionCadencesraised to 500 partitions and run once by hand, with 42 candles per partition — no data volume and no real network. ↩︎