Wiki Internals
The write path
How a candle batch travels from an INGEST frame to an acknowledgement — checks, admission, the write-ahead log, the hot cache, and the routes for history and restatements.
A live candle write has one rule that everything else serves: a candle reaches the in-memory hot cache only after its record is in the write-ahead log (WAL), and an acknowledged write is acknowledged only once that record is on disk. This page follows a batch from the network frame to the INGEST_ACK, and then covers the three other routes a write can take: history back-fills, restatements of stored bars, and ticks.
The journey at a glance
sequenceDiagram
participant C as Client
participant N as Network handler
participant D as Dispatcher / live writer
participant H as Hot cache
participant W as WAL writer
C->>N: INGEST frame (candles)
N->>N: parse + CRC, permission, placement, derived-stream check
N->>D: IngestCandles / IngestCandlesDurable
D->>H: hold arena, CanAdmit(batch)
D->>W: AppendBatch (buffered)
D->>H: AnchorBatch, SetAt per candle
D->>W: AwaitDurable(seq) (ack mode only)
W-->>D: group-commit fsync done
D-->>N: ok
N-->>C: INGEST_ACK(count)
1. The network handler
Server.handleIngest runs on the connection's own goroutine. In order, it:[1]
- Strips the optional epoch prefix (a fencing token used in clusters) and parses the
candle batch. A payload that fails to parse is answered
Protocolin-band; the connection stays open. - Checks the session's
WRITE_CANDLESpermission, granted at handshake. - Runs the placement checks (
placementChecked): whether this node serves the stream's partition, and whether the epoch the client carried is current. A refusal here is a redirect or a typed error, and it happens before anything is dispatched, so a refused batch provably stored nothing and re-sending it is a first attempt. An admitted write holds an in-flight token for its partition until the handler returns; a partition cutover waits on those tokens. See Partitions and routing. - Refuses a write to a derived stream unless the frame carries the overwrite flag.
- Picks the route from the frame flags: the correction flag goes to
IngestCorrection; the history flag selects the history workflow; ack mode selectsIngestCandlesDurable, and fire-and-forget selectsIngestCandles. Correction and history together are refused.
The outcome is mapped back onto the wire by one function, finishIngest, shared by every
route: a bad batch becomes an ERROR naming the reason, a shed becomes Overloaded with a
retry hint, anything else is logged and answered with a generic Internal error so that
paths and layout never leak to clients.
2. The dispatcher and the live writer
Dispatcher is the one object that knows both the write and the read side. On first sight
of a stream, GetLiveWriter builds a LiveStreamWriter: it creates the directory layout,
opens the stream's stream.idx and gap.idx through the dispatcher's single shared pair
(see the one-handle rule), resolves any chunk a
crash left half-installed, creates an unanchored hot cache sized for the stream, and
starts the stream's flusher, chunk GC (hourly) and index-compaction schedulers. Distinct
streams are built in parallel; one stream is built exactly once, under a per-stream creation
lock.
3. Admission, logging and apply — one critical section
logAndApplyCandles is the heart of the path. It holds two things for its whole duration:
the writer's appendMu, and the hot cache's arena hold (StreamCache.HoldArena), which
stops a compaction or drain from moving the cache's base while the batch is in flight.[2]
- Ask the cache first.
StreamCache.CanAdmitchecks every candle against the arena the batch will land in — for an unanchored cache, the arena it will get, based at the batch's earliest candle. The WAL is the irreversible half, so a batch the cache would refuse is refused before any of it is logged.[3] - Log it. The batch is encoded as one or more
CandlePayloadrecords and handed towal.Writer.AppendBatch, which admits the whole set as one unit or none of it. - Place it.
AnchorBatchgives an unanchored cache the baseCanAdmitchecked against, or moves an empty, drained cache's base forward past a long pause (keeping the skipped span as a hole to be filed as a gap later). It runs only after the WAL accepted the batch, so a shed batch leaves no base behind. - Apply it. Each candle goes through
StreamCache.SetAt: a new slot is appended, a slot that already holds a committed bar is routed to the cache's version chain as a correction. UsingSetAton both the live path and WAL replay is what lets a replayed correction rebuild exactly what the live path built.[4] - Publish the watermark. The batch's highest WAL sequence is stored as the writer's
cachedSeqonly after every candle is in the cache. The checkpoint relies on this value being contiguous: every sequence at or below it is in the cache.
"WAL first" means the record is in the WAL writer's buffer before the cache is touched, not that it is on disk. A concurrent reader can see a candle that is not yet fsynced. What waits for the disk is the acknowledgement (next section), never visibility.
Batch splitting
A WAL record carries at most 64 KiB of payload, while a wire frame may carry 16 MiB. The
two layers also disagree about row size: a candle is 49 bytes on the wire and 48 in the WAL,
while a tick is 24 bytes on the wire and 32 in the WAL (each WAL tick repeats its stream
hash so a record is self-describing during recovery). So the live writer splits a batch into
as many records as it needs (walCandlesPerRecord, walTicksPerRecord) and admits them
together; the highest sequence among them is the one the acknowledgement waits on.[5]
4. The acknowledgement
In ack mode, after the cache apply, the writer calls wal.Writer.AwaitDurable(seq). That is
a group-commit barrier: the WAL's background flusher swaps out its buffer, writes it to
the active segment, fsyncs (under the default sync_policy: always), and advances a durable
watermark; every waiter whose sequence is at or below it wakes. One fsync satisfies every
concurrent batch waiting on it. Only then does the handler send INGEST_ACK with the accepted
count.[6] Under sync_policy: interval or disabled the barrier promises only what that
policy does. See The write-ahead log.
Fire-and-forget writes return as soon as the batch is applied. They still go through the same bounded WAL buffer, so a producer faster than the disk is slowed and eventually shed rather than allowed to fill memory.
After a successful apply the dispatcher invalidates the stream's query-cache entries, records metrics, and tells the materialization deriver which timestamps changed. Subscribers receive the batch through the stream's feed, in log order, once it is durable.
5. Shedding and refusals
A write can be refused in two different ways, and the difference is the contract a client relies on.
| Refusal | Cause | Wire answer | What the client should do |
|---|---|---|---|
| Shed: WAL buffer full | The WAL writer's buffer stayed at wal. for wal. |
Overloaded + retry hint |
Re-send the whole batch; nothing was stored |
| Shed: hot cache full | CanAdmit answered ErrOutOfRange and the waits below did not help |
Overloaded + retry hint |
Re-send the whole batch; nothing was stored |
| Bad batch | Unaligned timestamp, too old for the cache and not a restatement, wider than the stream's arena (ErrBatchTooWide), a bar in a market closure, and others |
Protocol with a reason |
Fix or split the batch; retrying is pointless |
| History required | A restatement reaching bars in no chunk and outside the cache | HistoryRequired |
Send the range with the history flag |
| Durability failure | The WAL writer is poisoned | Internal |
Treat the node as failed |
The shed promise. Overloaded is raised before anything is stored, so re-sending the
batch is a first attempt, not a retry of an unknown outcome. Every retry rule in the SDKs
rests on that promise.[7]
Waiting before shedding. When the cache is full, the refusal has already asked the
flusher for an eviction (a compaction, or a full drain when the batch lies further past the
newest data than a compaction reaches, signalled by ErrNeedsDrain). Room usually appears
within milliseconds, so the writer releases the arena, sleeps admission_wait (10 ms by
default) and tries again, up to admission_retries (3) times, before answering
Overloaded. The retry hint is about one eviction: the duration of the last one, never less
than the server already waited, and never more than the flush interval.[8]
6. Writes onto stored history: restatements
A plain live batch that the hot cache refuses as too old (ErrTimestampTooOld) is not
returned to the client. It is turned into a restatement and sent through
LiveStreamWriter.restate, the same route a flagged correction takes, so a client never
needs to know whether a bar is still in memory or already in a chunk.[9] In order:
- Closure check. A bar landing in a filed market closure (an OFF_TIME gap) is refused before anything is written. Writing data into hours the exchange was shut would fabricate history that can never be told apart from real trading.
- Route every bar (
resolveRestatement, nothing written yet): a bar in a stored chunk joins that chunk's patch group; a bar the cache can address is applied there too; in the plain form a bar past the newest stored one is appended as new data. A bar that reaches neither a chunk nor the cache is refusedHistoryRequired. A bar off its chunk's interval grid is refused. The flagged (strict) form also refuses any bar past the newest stored one. - Skip unchanged bars.
ChunkPersister.Restatingcompares each chunk-bound bar with what the chunk serves; identical bars are dropped, so re-sending stored data costs a read, not a rewrite.[10] - Cache half first, durably. The cached bars go through the ordinary append path with the durability barrier. This half goes first because it is the only half that can be shed, and a shed must mean nothing was stored.
- Patches. Each touched chunk gets one new cumulative patch chunk (see patch chunks).
- Subscribers receive the bars that were written.
- Gaps last. Any OPEN gap the batch filled completely is marked CLOSED in
gap.idx, only after the data is durable. A partial fill leaves the gap OPEN — the safe direction.
The whole restatement runs while no evict-and-install is in progress for the stream
(ChunkFlusher.whileNotPersisting), because a flush moves bars from the cache to a chunk
and, mid-flight, they are in neither place.
7. History back-fills
A frame with the history flag skips the WAL and the hot cache entirely. history.Ingestor
stages candles in a pooled columnar arena per stream and hands full arenas to a pool of
compression workers, which build chunks and install them through the same ChunkPersister
protocol as the live flusher (Dispatcher.handleHistoryChunk). In ack mode the dispatcher
flushes the stream's staging arena and waits for the install before acknowledging, which is
a stronger receipt than the live path's: the data is in a chunk, not merely a log.[11]
A fire-and-forget history write has no WAL record. Until its chunk is installed it is only in memory, so a crash loses it. Use ack mode for history if you need the guarantee.
8. Ticks
Ticks take a shorter path: a WAL record in the stream's tick shard, then straight into the stream's tick storage buffer. They never enter the hot cache, which is keyed by a fixed interval that ticks do not have, and there is no admission window: a late tick is accepted and later stored in the chunk its time belongs to. See Ticks.
References
Source
Server.handleIngest,finishIngestLiveStreamWriter.logAndApplyCandles,appendCandles,restate,resolveRestatement,closeFilledGaps,refuseClosureFill,Dispatcher.ingestCandles,ShedRetryAfterChunkFlusherStreamCache.CanAdmit,AnchorBatch,HoldArena,SetAtwal.Writer.AppendBatch,AwaitDurableChunkPersister.Restating,PersistCorrectionhistory.Ingestor
Tests
TestServer_AckedCandleIngestIsInWALBeforeAck(tests/ack_durability_test.go) — the ack is a durability receipt.TestIngest_ArenaRejectionLogsNothing— a batch the cache refuses leaves no WAL record.TestIngest_NoCompactionLandsBetweenAdmittingABatchAndApplyingIt— the arena hold.TestIngest_AFirstBatchIsCheckedAgainstTheBaseItAnchors,TestIngest_AFirstBatchTheWALShedsLeavesNoBaseBehind.TestIngest_CorrectionDoesNotWedgeRecovery—SetAton both live and replay paths.TestIngest_SplitBatchIsOneContiguousWatermark,TestWriter_AppendBatchIsAdmittedOrShedWhole.TestServer_ShedIngestAnswersOverloaded,TestIngest_ABatchWiderThanTheArenaIsRefusedNotShed.TestIngest_AFullHotCacheWaitsForTheFlushInsteadOfRefusing,TestIngest_AFarBatchWaitsForTheDrainItAskedFor,TestIngest_ARefusalNeverHintsLessThanTheServerAlreadyWaited,TestIngest_ZeroAdmissionRetriesRefusesWithoutWaiting.TestIngest_APlainBatchOverFlushedCachedAndNewBarsLandsWhole,TestCorrection_AFlaggedCorrectionRefusesABarPastTheStreamsNewestData,TestCorrection_UnappliableRestatementIsRefused.TestIngest_ResendingStoredBarsWritesNoPatch,TestIngest_ARestatementWhoseNewBarsAreShedWritesNothing.TestIngest_APlainWriteFillsAStoredOutageButNeverAMarketClosure,TestCorrection_RefusesToFillAMarketClosure.TestCorrection_ACorrectionOfBarsAFlushIsInstallingWaitsForTheInstall,TestCorrection_ABatchAcrossSeveralChunksRestatesEachOne.TestServer_AWriteToADerivedStreamIsRefusedWithoutOverwrite.TestServer_HistoryBackfillLandsAndQueriesBack,TestHistoryBackfill_AFailedInstallIsNotAcked.
Further reading
- Durability and acknowledgements
- Corrections, restatements and history
- The write-ahead log, The hot cache, Chunks and compression
- Error codes, Wire protocol
External
- Pat Helland, "Life beyond Distributed Transactions: an Apostate's Opinion", CIDR 2007 — on idempotent re-sends as the basis of retry: https://www.cidrdb.org/cidr2007/papers/cidr07p15.pdf
Server.handleIngestin /internal/network/server.go. ↩︎StreamCache.HoldArena; proved byTestIngest_NoCompactionLandsBetweenAdmittingABatchAndApplyingIt. ↩︎TestIngest_ArenaRejectionLogsNothing. ↩︎TestIngest_CorrectionDoesNotWedgeRecovery. ↩︎walCandlesPerRecordin /internal/ingestion/dispatcher.go;TestIngest_SplitBatchIsOneContiguousWatermark. ↩︎TestServer_AckedCandleIngestIsInWALBeforeAck. ↩︎ShedRetryAfterandErrOverloadedin /internal/ingestion/dispatcher.go;TestServer_ShedIngestAnswersOverloaded. ↩︎LiveStreamWriter.admissionRetryHint;TestIngest_AFullHotCacheWaitsForTheFlushInsteadOfRefusing. ↩︎TestIngest_APlainBatchOverFlushedCachedAndNewBarsLandsWhole. ↩︎TestIngest_ResendingStoredBarsWritesNoPatch. ↩︎Dispatcher.IngestCandlesDurable;TestHistoryBackfill_AFailedInstallIsNotAcked. ↩︎