Wiki Cluster
Replication
How a partition's copies pull its data from the primary — seed rounds, the WAL tail, the replica log, the in-sync set, the replication factor, and exactly what a crash can lose.
A partition's data is replicated from its primary to its copies outside consensus, by the copies pulling it. A copy asks the primary for everything it has flushed that the copy does not hold (a seed round), then follows the primary's write-ahead log as it grows (the tail). Copies are byte-identical to their primary by construction: they install the primary's own chunk files and index entries, never re-encoding anything. Replication is asynchronous — a write is acknowledged once the primary has made it durable, without waiting for any copy — and this page says exactly what that costs.
The replication plane
Replication runs over its own gRPC listener, cluster.replication_addr, separate from the data
and control listeners. It is mutual TLS only: setting replication_addr requires
replication_cert_file, replication_key_file and replication_ca_file, there is no plaintext
mode, and a peer is identified by the node id in its certificate's common name
(mirexa-node-<id>), minted with mirexa-cli certs. The key file
must be mode 0600. Certificates can be rotated with SIGHUP; trusting a new CA needs a
restart.[1] Empty replication_addr means the node serves no replication at all: it can be a
primary, but nothing can copy from it, and it keeps no copies itself.
Each node holds one gRPC connection per peer address, shared by every partition that tails from that peer, with HTTP/2 keepalive as its health check. gRPC floors the client keepalive interval at 10 s, so a peer that goes silent without closing is detected no sooner than about 10 s plus the keepalive timeout.[2]
The service has five RPCs. Every one carries the partition and the epoch the caller
believes; a node that is not that partition's primary at that epoch refuses with a NotPrimary
detail naming the current epoch and primary — the replication plane's version of a redirect.
| RPC | Direction | Purpose |
|---|---|---|
Seed |
copy → primary | Bulk-transfer a partition's flushed artifacts the copy does not hold |
Tail |
copy → primary | Stream WAL records written after a watermark, plus heartbeats |
Drain |
new primary → old primary | Freeze a partition for a cutover |
Resume |
new primary → old primary | Reopen a drained partition (cutover rollback) |
FetchArtifact |
primary ↔ copy | Fetch one verified chunk to repair a rotten one |
Drain and Resume are covered in
Moving partitions and rebalancing;
FetchArtifact in Reconciliation, scrubbing and repair.
Seed rounds
A seed round copies flushed state: for each stream of the partition, its metadata record,
its chunk files and their stream.idx entries, its gap records, and its flushed tick chunks.
Every payload is the engine's own on-disk encoding inside an opaque bytes field, so there is one
codec per artifact and a copy is byte-identical to its primary.[3]
- Floors make it a delta. The copy reports, per stream, the highest chunk sequence number
(
SeqNo) it already holds; the primary sends only artifacts above it. Chunks are immutable once flushed, which is what makes copying them while the primary keeps writing safe. - Chunks are verified at both ends. The primary verifies each chunk against its own CRCs and
against the index entry that names it before sending; a chunk that fails ends the seed with
DataLossand is queued for repair rather than shipped to every copy. The copy verifies again before writing. - Transfer integrity. Chunks travel in pieces of at most 256 KiB, each with a CRC-32C.
- What the copy holds below its floor is checked too. Each stream's seed carries a reference: the highest SeqNo the primary has ever issued, and for each artifact at or below the copy's floor its index entry and the chunk footer's data checksum. A copy holding another history refuses the round before installing anything. See Reconciliation.
- Retention is mirrored. The reference carries where the primary's oldest chunk begins, and a copy that accepted the reference retires what the primary's retention dropped.
- Gap records are replaced, not merged, so a gap the primary closed by a fill is closed on the copy too.
- Install path. The copy installs through the same per-stream index pair its dispatcher uses
(never a second handle on
stream.idx), under the same install guard chunk garbage collection takes.
A copy runs its first seed round when it is added, then another every 30 s while tailing, and
again whenever the primary's log has moved past the copy's tail cursor. The periodic round is
what carries artifacts that never pass through the WAL — correction patches and history
back-fills — so those reach a copy within about one seed interval. (The schema defines an
ArtifactInstalled notice for them; the production tail source does not send it, so the 30 s
round is the mechanism.)[4] After every seed round that lands, the copy trims replica-log
segments whose every record a seeded chunk now holds.
The tail and the replica log
The tail streams raw WAL records for the partition — candle batches, tick batches, gap events — filtered from the primary's logs, polled every 50 ms. Every second, idle or not, it sends a heartbeat carrying the primary's durable watermark: what it has fsynced, not merely accepted. When a poll reads past only other partitions' records, the tail still sends an empty batch with the position it reached, so a copy of a quiet partition on a busy primary can be level.[5]
A copy does not ingest tail records. It appends them verbatim to a per-partition replica
log (partition_<id>/replica.wal, 64 MiB segments), fsyncs, and advances its cursor. Ingesting
would create a live writer whose flusher cuts chunks whose SeqNos collide with the primary's;
instead, chunks reach a copy only from the primary, through seed rounds. Tick records go to
partition_<id>/replica.ticks/n<origin>-<log>/, one log per primary log they came from, because
a WAL sequence number means something only within its own log on its own node.[6]
When a copy is promoted (by a cutover or a failover), its replica log is replayed through the
same recovery path a crash's WAL takes: only candles no seeded chunk already covers are
re-ingested, tick records are replayed at their original positions, and the log is deleted once
replayed. Until that replay finishes, the new primary refuses every request for the partition
with a retryable Overloaded and a 250 ms hint, so a client never reads a primary that is missing
its predecessor's last acknowledged writes.[7]
The tail cursor is a watermark: a node id, the candle WAL sequence and one sequence per tick WAL shard. It is node-bound — a watermark presented to a different node is refused, because WAL sequence numbers mean nothing elsewhere.
The in-sync set
A copy is in sync while it has recently been level with its primary: holding everything the primary had made durable as of some heartbeat. The in-sync set is the set a failover promotes from, and the set whose members may answer reads. It does not gate acknowledgements.
- Joining. A copy proposes itself in sync (
JOIN_IN_SYNC) once it is level with the primary's durable watermark — only the copy knows its own durable position, so it reports it. It proposes once per epoch; a primary change resets the set to the new primary alone, and each copy then re-earns its place. - Earned continuously. "Level" is dated by the heartbeat it covered, not by the instant it was
observed: a copy keeping up with a busy primary is almost never level at the moment a heartbeat
arrives, but it does cover each heartbeat shortly after. A copy that has not been level for
2 × liveness_timeout + 2 s(62 s at the default) proposes itself out (LEAVE_IN_SYNC) — for example after its replication certificate expires or a firewall blocks its port. - But not when the primary dies. A copy leaves only while the registry still believes its primary. When the primary dies every copy stops being level at once, and none of them fell behind; leaving would remove every failover candidate at the moment one is needed. The bound is chosen to outlast the fence of a dead primary.[8]
The bound also limits what a failover can lose: a copy promoted from the set was level within that window.
The replication factor
cluster.replication_factor is how many nodes hold each partition: one primary plus factor − 1
copies on distinct nodes. Default 1 (no copies), range 1–7. It is a cluster setting — seeded from
the founding node's YAML, then agreed, and immutable. Raising it would be possible for the
repair loop; lowering it would need a policy for which copy to drop, so both are refused.[9]
A leader-local loop (every 2 s) adds missing copies with ordinary ADD_SECONDARY entries:
- Partitions with the fewest copies first, then by id.
- Each copy goes to the
ONLINEnode holding the fewest partitions in any role that does not already hold this one; ties go to the node holding the fewest copies of this primary's partitions, so each node's copies spread evenly over the others rather than pairing nodes in a ring; then lowest id. - A partition whose primary is not
ONLINEis skipped — a seed reads the primary — and waits for failover. - At most twice
max_concurrent_migrationscopies may be syncing on online nodes at once, since every new copy is a full seed. - It never removes a copy. A partition above the factor (an operator's extra copy) is left alone.
- A divergent copy and a copy on an
OFFLINEnode both count as present. The divergent copy re-enters on its own after its data is quarantined; the offline node's copy is replaced only when an operator drains that node. A node that stays down is not replaced automatically.
mirexa_cluster_copies_missing reports the shortfall (NaN when the node cannot read its
control-plane state).
Ticks
Ticks replicate like candles: flushed tick chunks travel in seed rounds above a per-stream tick floor, tick WAL records travel in the tail tagged with the primary log they came from, and each tail batch names its tick streams so a copy can register a tick stream no seed round has shown it yet. On promotion, tick records no seeded tick chunk holds are replayed at their original positions and flushed before the logs are deleted, so neither a crash mid-promotion nor a second run replays a tick twice. Scrubbing and repair cover candle chunks only; stale reads never serve ticks.
What a crash can lose
Because acknowledgements do not wait for copies, a primary that crashes loses the writes it acknowledged after its copy last pulled them. This is the trade that keeps replication out of the write path.
-
The bound. A failover promotes only an in-sync copy, which was level with the primary within
2 × liveness_timeout + 2 s. No acknowledged write older than that can be lost, and the promoted copy holds a prefix of each stream — nothing past a gap. -
What it costs in practice — measured 2026-10-20 in the shipped binary on one development laptop (seven runs, two loads;
TestServerBinary_ACrashedPrimaryLosesOnlyWritesItsCopyHadNotPulled, a primary SIGKILLed under load with its in-sync copy on another node):Acknowledged write rate Candles lost ~600 – 2,300 candles/s (4 writers, 10-candle batches) 0 – 110 ~98,000 – 128,000 candles/s (8 writers, 500-candle batches) 0 – 3,000 (up to six batches) Every lost candle had been acknowledged 2–40 ms before the kill — about one tail poll's worth. Seven runs on one machine are a sample, not a distribution.
-
A clean stop loses nothing. On SIGTERM a clustered node first hands off: it stops admitting writes for its partitions (each is shed with the retryable drain answer so a routing client re-sends wherever the partition goes), waits for writes already admitted to finish, then waits — up to
network.shutdown_timeout(30 s) — until every copy tailing it has been sent everything it made durable. If that wait times out it logs an ERROR naming how many copies were behind and stops anyway.[10]
If no copy exists (
replication_factor: 1and no operator-added copy), a partition whose primary is lost has nowhere to fail over to. It staysUNAVAILABLEuntil that node returns.
References
Source
- Replication service schema
replication.Server,SeedSource,ErrArtifactCorrupt, tail loopreplication.Catchup,replication.Pool,replication.LoadNodeTLScluster.InSyncStaleAftercluster.State.PlanReplication, replication loopreplicaTailApply, replica supervisor, tick replica logs,replicationTailSourcenetwork.Server.Handoff,shutdown
Tests
TestReplica_ConvergesOnAMovingTarget— /cmd/server/replication_test.goTestSeed_AnArtifactThatFailsVerificationEndsTheSeedAsDataLoss— /internal/replication/seed_test.goTestTail_APollThatReadsOnlyOtherPartitionsSaysHowFarItRead— /internal/replication/tail_server_test.goTestCatchup_KeepingUpUnderLoadIsLevel,TestCatchup_ACopyThatLagsIsDatedByItsLag,TestCatchup_ADeadPrimaryKeepsItsCopiesInSync,TestCatchup_AQuietPartitionOnABusyPrimaryJoinsTheInSyncSet,TestInSyncStaleAfter_OutlastsTheFenceOfADeadPrimary— /internal/replication/catchup_test.goTestReplicaLog_IsTrimmedOnceSeededChunksCoverIt— /cmd/server/replica_trim_test.goTestReplica_ACopyHoldsItsPrimarysFlushedTicks— /cmd/server/tick_seed_test.goTestFailover_APartitionCarryingTicksFailsOverWithEveryAckedTickOnce,TestCutover_APartitionCarryingTicksMovesWithEveryAckedTickOnce— /cmd/server/tick_failover_test.goTestPartitionResolver_APrimaryServesNothingUntilItsReplicaLogIsReplayed— /cmd/server/replica_logs_test.goTestPlanReplication_SpreadsEachNodesCopiesOverTheOthers,TestPlanReplication_*,TestSettings_ReplicationFactor*— /internal/cluster/replication_test.goTestReplicationSweep_*— /internal/control/replication_test.goTestServerBinary_TheReplicationFactorGivesEveryPartitionItsCopies— /tests/server_binary_cluster_test.goTestServerBinary_ACrashedPrimaryLosesOnlyWritesItsCopyHadNotPulled— /tests/server_binary_crash_loss_test.goTestServerBinary_ASigtermedPrimaryUnderLoadLosesNoAckedWrite— /tests/server_binary_sigterm_test.go
Further reading
- Durability and acknowledgements
- Failure detection, leases and failover
- Reconciliation, scrubbing and repair
- The write-ahead log
- TLS and certificates
External
- Apache Kafka documentation, "Replication" (follower fetch, in-sync replicas) — https://kafka.apache.org/documentation/#replication
- gRPC, "Keepalive" (client keepalive minimum interval) — https://grpc.io/docs/guides/keepalive/
- Guy Castagnoli, Stefan Bräuer, Martin Herrmann, "Optimization of Cyclic Redundancy-Check Codes with 24 and 32 Parity Bits", IEEE Transactions on Communications, 1993 (CRC-32C)
ClusterConfig.ReplicationAddrand the TLS fields ininternal/config/config.go;LoadNodeTLSininternal/replication/tls.go. ↩︎internal/replication/pool.go. ↩︎StreamArtifacts,seedPieceSizeininternal/replication/seed.go; schema header inproto/mirexa/replication/v1/replication.proto. ↩︎CatchupOptions.SeedInterval(default 30 s) ininternal/replication/catchup.go;replicationTailSource.Installedreturns nil incmd/server/replication.go. ↩︎ServerOptions(50 ms poll, 1 s heartbeat) ininternal/replication/seed.go;tailer.readPastininternal/replication/tail_server.go. ↩︎replicaTailApply,replicaSegmentBytesincmd/server/replica.go;cmd/server/replica_ticks.go. ↩︎partitionResolver.ResolveStreamincmd/server/resolver.go;cmd/server/replica_logs.go. ↩︎CatchupOptions.StaleAfterininternal/replication/catchup.go;cluster.InSyncStaleAfterininternal/cluster/lease.go. ↩︎Settings.ReplicationFactorininternal/cluster/settings.go;State.PlanReplicationininternal/cluster/replication.go;MaxInFlight: 2 * limitininternal/control/replication.go. ↩︎Server.Handoffininternal/network/fencing.go; step 2 ofshutdownincmd/server/main.go. ↩︎