Mirexa

Wiki Internals

The hot cache

The per-stream columnar arena that holds recent candles in memory — anchors, floors and holes, sizing, admission, compaction into chunks, in-flight batches and in-place corrections.

Every live candle stream has a hot cache: a fixed-size, columnar, in-memory window over the stream's most recent bars. Live writes land there (after the WAL), queries read the newest data from it, and a background flusher moves the oldest bars out of it into compressed chunk files. The cache is also where a hole in the data is first noticed and classified. Ticks never use it; they have their own buffer (see Ticks).

The arena: slots, not rows

A stream's cache is a StreamCache, which wraps one arena (StreamCacheArena). An arena is allocated whole at a fixed number of slots, one per interval of the stream's timeframe, starting at a base timestamp:

text
slot i  ⇔  timestamp = base + i × interval

open   [ 1.10 | 1.11 |  —   | 1.13 | … ]   five float64 columns, 40 bytes a slot
high   [  …   |  …   |  —   |  …   | … ]
low    [  …   |  …   |  —   |  …   | … ]
close  [  …   |  …   |  —   |  …   | … ]
volume [  …   |  …   |  —   |  …   | … ]
gap    [  0   |  0   |  1   |  0   | … ]   one atomic bit per slot
len    = 4    (slots committed, gaps included)

There is no timestamp column: a slot's timestamp is arithmetic, so finding a bar is (ts − base) / interval — O(1) — and the arena saves 8 bytes a slot. The index is computed in 64 bits and compared with the capacity before it is narrowed to 32, so a timestamp absurdly far ahead is out of range rather than wrapped onto a stored bar.[1] The columnar layout also lets each column be compressed on its own terms when it is flushed.

Gap marking. Writing slot 7 when len is 4 marks slots 4–6 as gaps, writes the data, clears slot 7's gap bit, and only then publishes len = 8 with an atomic store. len is the synchronization point: a reader that observes len > i is guaranteed to see slot i's data and gap bit. Readers never take a lock.

Len() counts committed slots including gaps, so an arena anchored before its first bar reports a length covering ground it holds no data for. Ask DataSpan() where the data actually is.

Gap compaction in place. A sparse arena (an illiquid symbol, a stream outside its session) can hold thousands of empty slots. On each flush tick, if the share of gap slots reaches gap_compaction_ratio, CompactGapsInPlace copies the arena without its gap runs and publishes the copy with one atomic pointer swap. After that the arena has two index spaces — the original index on the timeline, which the API speaks, and the physical index into the columns — translated by a gap-region tracker. It runs at most once per arena.[2]

Anchors, floors and holes

Anchoring. A live stream's first bar time is unknown when the stream is created, so a new cache is unanchored. It is anchored by its first admitted batch, at the aligned slot of that batch's earliest candle (AnchorBatch), which is exactly where admission checked the batch. A WAL replay anchors explicitly at the earliest candle it restores (Anchor).

Floors. An anchor lives only in memory, so a restart loses it — and an unanchored cache would accept any first write, including one into data already flushed to chunks. The live writer therefore sets a floor at the end of the stream's newest chunk when it builds the cache (SetFloor): while unanchored, the cache refuses a candle at or below it. A replay's explicit anchor ignores the floor, because what it restores can lie below a back-filled chunk.[3]

Holes. A cache holding no data — drained by a checkpoint, say — takes a batch however far ahead it lies: AnchorBatch moves the base forward to the batch. The span between where the data ended and the new base was never in any arena, so no gap bit can describe it. The cache records it as a hole and hands it to the next compaction that evicts candles, which files it in gap.idx through the same classifier as every other gap. The same applies to any anchor above the floor, which is how a pause across a restart is filed.[4] Until it is filed, a hole is published to readers (PendingGaps) and a query reports it as an unclassified OPEN gap.

Nothing on the ingest path bounds how far in the future a timestamp may be. A drained stream will accept a bogus bar a year ahead, record a year-long OPEN gap before it, and then refuse the real next bar as older than its base.

Sizing

An arena costs 40 bytes per slot whether or not the slot is filled, and its capacity is also the widest batch the live path accepts. Mirexa sizes each stream's cache by time (ingestion.cacheSizing):[5]

  • Derived by default. Slots = cache_span ÷ the stream's interval, rounded up, at least 2,048 and at most cache_arena_capacity (50,000 by default; the ceiling wins if it is below the floor). With cache_span unset, the span is what cache_arena_capacity one-minute slots cover, so one-minute and faster streams get exactly cache_arena_capacity and only slower streams shrink.
  • Kept after a compaction: the same share of slots that cache_hot_cache_size is of cache_arena_capacity (25,000 of 50,000, i.e. half, by default).
  • Overridden per stream by an operator with mirexa-cli cache set -stream … -slots N (16 to 8,388,608 slots, 0 to clear). The override is stream metadata, survives restarts, and goes to replicas with the seed. Only that command writes it; the data protocol cannot.

With the defaults:

Timeframe Slots Kept after compaction Columns in memory
1s, 1m 50,000 25,000 ~2 MB
5m 10,000 5,000 ~400 KB
15m 3,334 1,667 ~133 KB
30m and longer 2,048 1,024 ~82 KB

A size change reaches a running stream before the call returns: an empty arena is replaced at once, and one holding data is drained into a chunk so the next arena is built at the new size. Every candle stays readable throughout.[6] Memory at scale has not been measured; the figures above are arithmetic.

Admission

The live writer must know whether the cache will take a whole batch before it writes the batch's WAL record, because the WAL cannot be un-written. CanAdmit answers that, against the arena the batch will actually land in, and distinguishes refusals a retry can cure from ones it cannot:[7]

Error Meaning Answer to the client
ErrOutOfRange The batch fits one arena and lies past this one; evicting the oldest bars makes room Shed (Overloaded) after brief waits
ErrOutOfRange + ErrNeedsDrain Only evicting every bar makes room (the batch is further past the newest data than a compaction reaches) Shed; the flusher is asked for a drain, not a compaction
ErrBatchTooWide The batch spans more slots than any arena of this size holds Protocol: split the batch
ErrTimestampTooOld A bar lies below the base (or the batch reaches back into held slots and past the end at once) Routed to a restatement on the plain live path; otherwise Protocol
ErrUnaligned A timestamp is not on the stream's interval grid Protocol

ErrOutOfRange is answered only when nothing else is wrong with the batch: the whole batch is read before that answer is given, so a batch that is also too wide or unaligned is refused as what it is.

Holding the arena. A verdict is true only while the base does not move, and the flusher compacts on its own timer. So the live writer holds the arena (HoldArena) from the check, through the WAL append, to the last candle applied; Compact and Drain take the same lock first and wait. Readers never take it. The cost is that a compaction can wait behind a batch's WAL append, up to wal.buffer_wait_timeout under backpressure.[8]

Compaction and drain: from cache to chunk

The stream's ChunkFlusher goroutine evicts bars from the cache into chunks. It acts on four triggers:

  • every flush interval (5 s by default): a compaction if the arena holds more slots than it keeps, plus the in-place gap compaction above;
  • a non-blocking "full" signal from the write path: a compaction;
  • a "drain" signal from the write path, or a checkpoint (DrainNow): a drain;
  • shutdown: a drain.

A compaction evicts the oldest slots and keeps the newest HotCacheSize slots for read latency; a drain keeps nothing. For a one-minute stream at defaults a compaction evicts nothing until 25,000 slots (about 17 days) have accumulated, so in practice the 15-minute checkpoint drain is what cuts most live chunks.

Inside compactRetaining, under the hold and the writer lock:[9]

  1. Merge pending corrections (the version chain) into the base so the evicted bars carry their latest values.
  2. Classify the evicted range's gap runs with the stream's calendar: a run overlapping trading hours is a missing-data gap (OPEN), a run wholly in closed hours is OFF_TIME (PERMANENT); without a calendar, duration thresholds decide.
  3. Gap runs that have not ended are not classified yet: a run still open at the cut is kept as a hole and joined with its continuation in a later compaction, so one pause is classified once, by its whole length.
  4. Build the next arena from the current sizing, copying the kept slots into it.
  5. Publish the evicted bars, and their classified gaps, as an in-flight batch, then swap the new arena in.

The flusher then builds a chunk from the result and installs it with the persister's protocol, files the gaps, and only then releases the in-flight batch by id. A stream's evict-and-install is one critical section (ChunkFlusher.persistMu), shared by compaction, drain and checkpoint.

The in-flight batch keeps reads whole

Between eviction and install — a chunk build plus fsyncs — the evicted bars are in no chunk and no arena. The in-flight batch closes that window: every cache read (Get, RangeScan, DataSpan, ScanWithSpan) merges it. The ordering is the guarantee: a compaction publishes the batch before swapping the arena, and readers load the arena before the batch list, so a reader that sees the shrunken arena also sees the batch.[10]

If the install fails, the batch is deliberately not released: the bars stay readable from memory, they stay in the WAL (the checkpoint refuses to advance past a stream with an unreleased batch), and a restart's replay rebuilds them. Nothing retries a failed install before then.

Corrections inside the cache: version arenas

Overwriting a committed slot is not safe the way appending is: the columns are read with plain loads, so a plain store into a slot a reader might be reading is a data race, not just a stale read. So StreamCache.SetAt sends an update to an already-committed slot to a version arena (VersionArena): a sparse overlay of atomic.Pointer[Candle], one pointer per slot. Versions form a copy-on-write chain, newest first on reads; after three versions (max_versions) the chain is merged into a fresh copy of the base, published with one pointer swap. Every compaction merges first, so a correction is never lost as it is flushed.[11] This is the "MVCC" in Mirexa: in-place correction of committed bars without blocking lock-free readers — not snapshot isolation across queries.

Concurrency summary

Operation Lock Readers blocked?
Get, RangeScan, ScanWithSpan, DataSpan, PendingGaps none (atomic loads) —
Append, SetAt, AnchorBatch, CanAdmit, Merge writerMu no
Compact, Drain, SetSizing holdMu then writerMu no
A live batch, check to last apply holdMu (via HoldArena) no

Mutations that rewrite committed state (merge, gap compaction, compaction) build a private copy and publish it with one atomic pointer swap, so no reader ever sees a slot mid-write.[12]

References

Source

Tests

  • TestStreamCache_AnIndexPast32BitsIsOutOfRangeNotWrappedOntoAStoredBar.
  • TestCompactGapsInPlace_IsIdempotent, TestCompactGapsInPlace_ConcurrentReaders, TestGapConsolidation_ImplementationsAgree.
  • TestStreamCache_AFloorBarsAnUnanchoredCacheFromFlushedData, TestStreamCache_AReplayAnchorsBelowTheFloorAndTheFloorStopsApplying.
  • TestStreamCache_AnEmptyCacheTakesABatchPastItsArenaAndKeepsWhatItSkips, TestStreamCache_AHoleWaitsForACompactionThatEvictsCandles, TestStreamCache_AnAnchorAboveTheFloorKeepsTheSpanBelowIt, TestIngest_AResumedStreamFilesTheAbsenceBeforeIt, TestQuery_APauseStillGoingOnIsReportedWhole.
  • TestCacheSizing_IsDerivedFromTheTimeframe, TestDispatcher_AStreamsCacheIsSizedFromItsTimeframe, TestDispatcher_ACacheCapacityOverrideSurvivesARestart, TestDispatcher_ACacheCapacityOverrideTakesEffectAtOnceAndKeepsEveryCandle, TestDispatcher_OnlySetStreamCacheCapacityWritesTheOverride, TestStreamCache_AdmissionPredictsTheArenaAPendingSizeGives, TestStreamCache_ASizeChangeWaitsForAHeldArena.
  • TestCanAdmit_AnswersOutOfRangeOnlyWhenARetryCanHelp, TestCanAdmit_SaysWhichEvictionMakesRoom, TestStreamCache_AnUnanchoredCacheIsCheckedAtTheBaseTheBatchGivesIt, TestIngest_AFarBatchOnACacheStillHoldingDataIsShedOnlyUntilADrain.
  • TestStreamCache_CompactAndDrainWaitForAHeldArena, TestIngest_NoCompactionLandsBetweenAdmittingABatchAndApplyingIt.
  • TestFlusher_ClassifiesGapsWithMetadata, TestFlusher_APauseLongerThanTheHotCacheIsFiledWhole, TestFlusher_APauseIsClassifiedByItsWholeLength.
  • TestCompact_EvictedCandlesStayReadableUntilRelease, TestCompact_ReadsNeverDipDuringConcurrentCompaction, TestCompact_EvictedGapsStayVisibleUntilRelease, TestDrainNow_DoesNotReturnWhileAConcurrentDrainIsStillInstalling.
  • TestIngest_CorrectionReplacesTheStoredCandle, TestIngest_CorrectionSurvivesFlushToChunk.
  • TestMergeVsGet_DataRace, TestAppendVsCompact_DataRace, TestConcurrentWriters_AppendCompactSetAtGet.

Further reading

External

  • D. Abadi, S. Madden, N. Hachem, "Column-Stores vs. Row-Stores: How Different Are They Really?", SIGMOD 2008: https://doi.org/10.1145/1376616.1376712
  • The Go memory model (why len is published with an atomic store): https://go.dev/ref/mem

  1. StreamCacheArena.computeIndex; TestStreamCache_AnIndexPast32BitsIsOutOfRangeNotWrappedOntoAStoredBar. ↩︎

  2. TestCompactGapsInPlace_IsIdempotent, TestCompactGapsInPlace_ConcurrentReaders. ↩︎

  3. TestStreamCache_AFloorBarsAnUnanchoredCacheFromFlushedData, TestStreamCache_AReplayAnchorsBelowTheFloorAndTheFloorStopsApplying. ↩︎

  4. TestStreamCache_AnEmptyCacheTakesABatchPastItsArenaAndKeepsWhatItSkips, TestIngest_AResumedStreamFilesTheAbsenceBeforeIt. ↩︎

  5. TestCacheSizing_IsDerivedFromTheTimeframe. ↩︎

  6. TestDispatcher_ACacheCapacityOverrideTakesEffectAtOnceAndKeepsEveryCandle. ↩︎

  7. TestCanAdmit_AnswersOutOfRangeOnlyWhenARetryCanHelp, TestCanAdmit_SaysWhichEvictionMakesRoom. ↩︎

  8. TestStreamCache_CompactAndDrainWaitForAHeldArena. ↩︎

  9. StreamCache.compactRetaining in /internal/cache/cache.go; TestFlusher_APauseIsClassifiedByItsWholeLength. ↩︎

  10. TestCompact_EvictedCandlesStayReadableUntilRelease. ↩︎

  11. TestIngest_CorrectionSurvivesFlushToChunk. ↩︎

  12. TestMergeVsGet_DataRace, TestConcurrentWriters_AppendCompactSetAtGet. ↩︎