Mirexa

Wiki Cluster

Partitions and routing

How a stream is mapped to a partition, how the partition directory names its primary, and how clients find the right node through redirects and fencing epochs.

Every stream in a Mirexa cluster belongs to exactly one partition, and every partition is served by exactly one primary node at a time. Routing is the question "which node serves this stream right now?". A node answers it from its own copy of the partition directory; a client learns the answer one redirect at a time and caches it with an epoch, a number that lets the client tell a current answer from a stale one. This page covers the mapping, the directory, how a request finds its node, and how multi-stream reads are split across nodes.

From stream to partition

A stream is identified by symbol, timeframe and exchange. Its partition is

text
partition = FNV-1a-64(symbol ‖ 0x00 ‖ exchange) mod partition_count

The timeframe is deliberately left out of the key, so every timeframe of one instrument on one exchange — BTCUSDT:1m, BTCUSDT:1h, BTCUSDT:1d on binance — lands in the same partition. That keeps a stream and the streams derived from it on one node.[1]

partition_count (partition.count, default 4096) must be a power of two and is a cluster setting: agreed once, through the control plane, and immutable afterwards. Changing it would map every stream to a different partition, which is a full data migration, not a configuration change; the state machine refuses it.[2] A uniform-distribution test checks 40,000 distinct keys against a chi-squared bound, and a golden-literal test pins the hash across builds so an accidental change of hash function cannot silently re-map every stream.

The partition directory

The directory is part of the replicated control-plane state. One entry per partition:

Field Meaning
Primary The one node that accepts writes.
Secondaries Nodes holding a copy, replicated outside consensus.
InSync The primary plus the copies currently caught up.
Epoch The fencing token: the Raft log index of the entry that installed the current primary.
Divergent Nodes a failover set aside because their data may differ from the new primary's.

The epoch is a log index, not a counter. Only the state machine's Apply knows the index of the entry it is applying, so an epoch cannot be chosen by a proposer and cannot repeat across a leader change; every replica derives the same value from the same entry, also after a snapshot restore. It advances only when the primary changes. Adding a copy, moving the in-sync set or removing a copy leaves it alone, because bumping it would make the still-legit primary refuse its own clients.[3]

Placement

A leader-local loop gives every unassigned partition a primary: the ONLINE node holding the fewest partitions, ties broken by lowest id. All of a bootstrap's placements go into one Raft entry. Placement never moves a partition that already has a primary — even one whose primary is down — because moving an assigned partition is a cutover (see Moving partitions and rebalancing) and replacing a dead one is failover (see Failure detection, leases and failover).[4]

A node that joins a cluster whose partitions are all placed receives no partitions by placement. It holds data only once something moves partitions to it: an operator's MigratePartition, the rebalancer (advisory unless cluster.rebalance_auto is on), or the replication loop adding copies.

How a node answers

When a request names a stream, the receiving node resolves it locally — a hash and a map lookup in its own applied directory, never a consensus round:[5]

Situation What the node does
This node is the primary, holds a current lease, and has replayed any replica log Serves the request
Another node is primary and the cluster believes it (ONLINE or LEAVING) Answers REDIRECT naming partition, epoch, primary id and data address
Another node is primary and the cluster has fenced it Refuses with PartitionUnavailable (0x0009), no retry hint — it will not send a client to an address it has stopped believing
This node is primary but its lease is not in effect Refuses with PartitionUnavailable
This node just became primary and is still replaying its replica log Sheds with Overloaded (0x0007) and a 250 ms hint; it heals on its own
The partition has no directory entry yet Serves locally (a cluster before its first placement)
A write carries an epoch, and this node's entry is missing or older Refuses with StalePlacement (0x0008) and a retry hint — the node is behind, not the client
A read allows a stale answer and this node is an in-sync copy May answer from the copy — see Reads from copies

The redirect is emitted after the permission check and before anything is dispatched. "After" so that an unauthorized request gets the same answer wherever its data lives; "before" so that following a redirect is a first attempt, safe for a write, rather than a retry of something that may have been applied.[6]

The REDIRECT frame

REDIRECT_COMMAND (0x20) is a frame of its own, not an error code: an error frame has only a code, a message and a retry hint, and a redirect is not retryable, it is re-targetable. Its payload is partition (4 bytes), epoch (8), node id (8), address length (2), the data address, and a CRC-32C. The checksum matters because of the epoch: a client refuses any route older than the one it holds, so a single flipped high bit in an epoch would store a value no honest answer could ever exceed and wedge that partition in the client's cache until restart. Only the data address is sent; the control and Raft addresses are not a data client's business.[7]

Fencing writes with the epoch

A write may carry the epoch its sender believes, as a 12-byte prefix (epoch + CRC-32C) in front of the ordinary candle or tick payload, signalled by frame flag FlagEpoch (0x08). The prefix sits above both payload formats, so candle and tick writes are fenced by one mechanism.[8]

The primary compares the carried epoch with its own:

  • Equal — accepted.
  • Older — the sender is stale. The primary answers with a REDIRECT naming itself at the current epoch, which corrects the client's cache.
  • Newer — this node is behind. It answers StalePlacement with a retry hint.
  • No prefix — treated as unfenced and accepted: a client's first request has no epoch to send. A client that has been redirected once carries one from then on.

The epoch check stops stale clients, not stale servers. A primary that has not yet applied its own demotion carries the old epoch too, so an old-epoch write still matches it. What stops a superseded or cut-off primary is its lease: it stops serving before the cluster could replace it. See Failure detection, leases and failover.

The routing client

A client that is not a cluster member holds neither the partition count nor the directory, so it cannot compute where a stream lives. The routing client (wireclient.RoutingClient) starts from one or more contact points — any node will do — and learns the layout from the redirects it receives:[9]

  • Route cache. Each learned route is stored with its epoch. A route with an older epoch than the cached one is refused, so out-of-order answers cannot resurrect a corrected route. A refusal that is itself older than the cached route is ignored. "I could not reach it" carries no epoch and simply forgets the route.
  • One connection per node. Each node gets its own resilient connection, with its own reconnection policy and circuit breaker. When a node is unreachable or its breaker is open, the route is forgotten and the request starts again from a contact point, passing over contact points that do not answer.
  • Convergence rules for one request. Each hop must carry a strictly newer epoch than the last. An equal epoch from a different node means two directories disagree, and the request fails with ErrRedirectLoop. An older epoch means the answering node has not yet applied a move another node already reported — the window every partition move opens for about a heartbeat — so the client waits and asks again (20 ms doubling, six times, about 1.3 s in all) before giving up. At most three hops are followed (DefaultMaxRedirects).[10]
  • Writes carry the epoch once the partition is known; routing and fencing are not separately configurable.
  • Ambiguous writes are never re-sent elsewhere. A write whose connection failed mid-request (ErrAmbiguous) may have been applied; it is returned to the caller to reconcile by reading back.

Who routes today:

Client Follows redirects
wireclient.RoutingClient (used by mirexa-cli load, the web dashboard) Yes
Python SDK (mirexa) Yes — a port of the Go route cache and redirect walk
Public Go SDK (client package) No — a redirect surfaces as client.RedirectError, naming where to go
mirexa-cli No — talks to one node

A live subscription also follows its partition: a node ends a subscription whose partition has moved away with a redirect, and a resuming subscriber that follows redirects reconnects to the new primary and resumes from the last candle it delivered.

Multi-stream reads across nodes

A QUERY_MULTI names several streams that may live on several nodes. It is split, not re-targeted. The routing client's QueryMultiAll sends each sub-query to the node it believes serves it (or a contact point). A node serves the sub-queries it owns and answers each other one in place with status Elsewhere (0x04) plus the redirect a single query would have got; the rest of the batch is still served. The client regroups by node and asks again. A warm client sends one leg per node.[11]

  • Each sub-query follows the single-request rules above (strictly newer epochs, hop cap, contact point restart). Waiting out a lagging node happens once per round, not once per sub-query.
  • Nothing is merged: results are positional, one complete series per sub-query, each from the one node that serves its stream.
  • A leg is capped at FanOutMaxSubQueries (default 128, a node's default max_subqueries_per_request) and a larger part is sent as several legs, because a node refuses an over-cap batch whole.
  • FanOutLegTimeout, if set, bounds one node's leg so a slow node ends its own part rather than holding the call.

Partial results

When one node cannot answer — down past every contact point, its leg timed out, its partition unavailable — its sub-queries come back with status StatusUnanswered (0xFF, client-side only, never on the wire) and the other nodes' answers are kept. The call returns them together with a *PartialResultError naming each failed node, the positions it held and why. A caller checking only the error sees a failure; partial data is never handed back looking complete, and there is no knob that turns missing data into a nil error. The caller's own deadline expiring ends the whole call.

If a sub-query allows a stale answer, a dead node's sub-queries are retried on the serving nodes, any of which may answer from an in-sync copy. See Reads from copies.

Listing streams across nodes

ListAllStreams sends the same page request to every node the cluster lists (LIST_NODES, 0x48/0x49, answered from a node's applied registry and directory), with the ServedHere flag so a copy never answers for its primary. Pages are merged by stream id and de-duplicated before the limit is applied, so paging is by stream id only. An unreachable node, or a fenced node still primary of partitions, is named in a *PartialResultError. It is a deliberately costly call — one request per node.

References

Source

Tests

Further reading

External

  • Glenn Fowler, Landon Curt Noll, Kiem-Phong Vo, "The FNV Non-Cryptographic Hash Algorithm", IETF draft — https://datatracker.ietf.org/doc/draft-eastlake-fnv/
  • Martin Kleppmann, "How to do distributed locking" (fencing tokens) — https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
  • Apache Kafka protocol, NOT_LEADER_OR_FOLLOWER and metadata refresh — https://kafka.apache.org/protocol

  1. StreamID.PartitionKey and AssignPartition in internal/types/stream.go. ↩︎

  2. cluster.Settings.PartitionCount and State.SetSettings in internal/cluster/settings.go. ↩︎

  3. Assignment.Epoch in internal/cluster/partition.go. ↩︎

  4. State.PlanPlacement in internal/cluster/placement.go; the placement loop in internal/control/placement.go. ↩︎

  5. partitionResolver.ResolveStream and copyRead in cmd/server/resolver.go; codes in internal/wire/protocol.go. ↩︎

  6. internal/wireclient/redirect.go header; TestFencing_AClientCorrectedByARedirectThenFencedByTheEpoch. ↩︎

  7. internal/wire/redirect.go. ↩︎

  8. internal/wire/epoch.go; FlagEpoch in internal/wire/protocol.go. ↩︎

  9. internal/wireclient/routing.go and routecache.go. ↩︎

  10. RedirectWalk, DefaultMaxRedirects in internal/wireclient/redirect.go; behindRetries, behindBackoff in internal/wireclient/routing.go. ↩︎

  11. internal/wireclient/fanout.go; QueryStatusElsewhere in internal/wire/payload.go. ↩︎