Construct a remote feature flag evaluation network with eventual consistency guarantees: data distribution, conflict resolution, health monitoring, and failover strategy.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are going to design a remote feature flag evaluation network that ensures eventual consistency, handles conflicts, monitors health, and has failover strategies.
Components:
Feature Flag Store: A distributed key-value store that holds the feature flags and their configurations. We can use something like DynamoDB, Cassandra, or a custom implementation with a consensus protocol (Raft) for strong consistency in each partition but eventual across partitions? Actually, we want eventual consistency globally. So we can use a multi-master replication setup with conflict resolution.
Evaluation Service: Stateless services that evaluate feature flags for clients. They read from the feature flag store and cache results. They need to handle conflicts and updates.
Health Monitoring: Monitor the health of the evaluation services and the feature flag store. Also monitor network partitions and replication lag.
Conflict Resolution: In an eventually consistent system, updates can happen concurrently on different nodes. We need a way to resolve conflicts. We can use:
Vector clocks or timestamps (last-write-wins, but might lose updates). Alternatively, we can have application-specific merge functions (CRDTs) for the feature flag configurations? Feature flags are typically simple (on/off, or with rules) so we might use a simple rule: the update with the highest timestamp wins, but ensure that timestamps are from a synchronized clock (or use hybrid logical clocks). Alternatively, we can have a primary region for each flag and route writes to that primary, but that might reduce availability.
Data Distribution: We need to distribute the feature flag data across multiple regions for low latency. We can partition by feature flag ID. Each partition is replicated across multiple regions. We can use a multi-master replication where any region can accept writes and then replicate to others.
Failover Strategy: If a region goes down, we should route traffic to other regions. Also, if the feature flag store in a region is down, the evaluation services in that region should use cached data or failover to another region's store (if network allows). But note: we are building a remote evaluation network, so clients might call any evaluation service.
Design:
Feature Flag Store:
We'll design a distributed store with partitions (shards) by feature flag ID (or by customer ID if multi-tenant). Each partition is replicated across at least 3 regions.
Each replica can accept writes (multi-master). Writes are timestamped with a hybrid logical clock (HLC) or a vector clock to capture causality.
When replicating, we use an anti-entropy process (like in Dynamo) to synchronize and resolve conflicts. Conflict resolution: for feature flags, we might have a simple rule: the update with the highest HLC timestamp wins. If two updates have the same HLC, then we can break ties by region ID (or node ID) but that's arbitrary. Alternatively, we can define a merge function that takes the union of rules if the feature flag is a set? But feature flags are usually a boolean or a set of rules (targeting rules). We might need to merge rules? For example, if two concurrent updates add different targeting rules, we might want to keep both? But then the evaluation might become inconsistent. So perhaps we treat the entire feature flag configuration as an atomic value and use last-write-wins. But note: if two updates are concurrent, one might enable the flag and the other might change the rule, then we lose one update. So maybe we need to version the entire configuration and have a way to merge? That's complex.
Given the complexity, we might decide that feature flag updates are rare and we can have a stronger consistency model for each flag. But the requirement says eventual consistency, so we accept that there might be conflicts.
Alternatively, we can use a operational transform or CRDT for the configuration? For example, if the configuration is a set of rules (each rule is a condition and an outcome), then we can treat it as a set of rules. Then concurrent additions are merged, and deletions? Deletions might be tricky. We can use a add-wins set (or remove-wins) but then we need to track deletions separately. This might be overkill.
Given the time, let's assume we use a simple last-write-wins with HLC. We'll store the entire configuration as a blob and update it atomically.
Evaluation Service:
Stateless, runs in multiple regions. Each evaluation service instance has a local cache of feature flags (in-memory or Redis). The cache is updated by:
Pull model: the evaluation service periodically polls the feature flag store for changes (for the flags it cares about). But we have many flags, so we might have a pub/sub system: the feature flag store publishes changes (to a message queue like Kafka) and evaluation services subscribe. Alternatively, we can have a push model: when a flag is updated, the store notifies all evaluation services (or at least the ones in the same region) to invalidate their cache. But with eventual consistency, we might get multiple notifications? We need to handle that.
Better: the evaluation service reads from the local replica of the feature flag store (so low latency) and caches. The store's replica is updated by replication. When the evaluation service reads a flag, it gets the latest from the local replica (which might be stale). We can have a freshness requirement: if the flag is too old, we might want to read from a leader? But we don't have a global leader. Alternatively, we can have a quota on staleness: if the replication lag is too high, we might block evaluations? That's not good.
We can design that the evaluation service always reads from the local replica and returns the flag. Since we have eventual consistency, the flag might be outdated. But for feature flags, a slight delay in update propagation is acceptable (seconds). We can set a TTL on the cache and refresh periodically.
Health Monitoring:
Monitor replication lag between regions. If lag is high, we might trigger alerts.
Monitor the health of each region's store (node up/down, disk space, etc.) and evaluation services (response time, error rates).
If a region's store is down, we can route evaluation requests to another region? But the evaluation service is already in a region, and it reads from its local store. If the local store is down, the evaluation service might fail. So we need the evaluation service to have a fallback: if local store is down, try another region's store? But that adds latency and might break if network partition. Alternatively, we can have the evaluation service use a read-replica in another region? But that would cross regions and be slow.
Better: we run evaluation services in multiple regions, and each region has its own store replica. If the store in a region is down, we can take the evaluation services in that region out of rotation (load balancer) and route traffic to other regions. So we need a global load balancer that directs client requests to healthy regions.
Failover Strategy:
For writes: if a region is partitioned (cannot reach majority of replicas for a partition), then writes in that region might be rejected? Or we can allow writes and then resolve conflicts later (since multi-master). But we must ensure that writes are not lost. So we can allow writes in any region that has at least one replica of the partition (assuming we have a quorum for writes? Actually, for high availability, we might set write quorum to 1? But then we risk inconsistency). We can set write quorum to 2 (out of 3) to ensure that at least two replicas have the write before confirming. But then if a region is isolated, it might not be able to write. Alternatively, we can use a dynamic quorum: if a region is partitioned, it can still write to its local replica and then later reconcile. But then we need to handle conflicts.
Given the requirement for eventual consistency, we can have:
Write: always accepted by the local replica (write quorum = 1) and then asynchronously replicated to other replicas. The local replica confirms to the client immediately. This gives low latency and high availability but increases the chance of conflicts. However, with conflict resolution (last-write-wins) we are okay.
Read: from local replica, which might be stale.
So the system is AP (available and partition tolerant) with eventual consistency.
Conflict Resolution:
We use a hybrid logical clock (HLC) that combines physical time and logical counter. Each write gets an HLC timestamp. During replication, when two replicas have conflicting versions (different data for the same key), we pick the one with the higher HLC. If HLCs are equal, we break ties by region ID (or node ID) in a deterministic way.
Data Distribution:
We partition the feature flags by key (feature flag ID) using consistent hashing. Each partition is assigned to multiple regions (replication factor 3). The mapping of partitions to regions is stored in a metadata service (like ZooKeeper) or we can use a distributed hash table.
Implementation Plan:
Metadata Service: Maintains the current partition-to-region mapping. This service itself must be highly available (we can run it in each region with consensus). Alternatively, we can use a static configuration and update it manually? But we want dynamic rebalancing. We might start with a fixed assignment and change rarely.
Feature Flag Store per Region: Each region has a set of nodes (say 3) that store the partitions assigned to that region. They form a Raft group for strong consistency within the region? But then writes within a region are strongly consistent. However, we want multi-master across regions. So we cannot have a single Raft group per partition across regions because that would require cross-region consensus and reduce availability. Instead, we have independent nodes in each region that can accept writes for the partitions they own. They replicate asynchronously to the same partition in other regions.
So each partition is stored in multiple regions, and each region has a local Raft group for that partition? Actually, if we have 3 replicas of a partition, they are in 3 different regions. In each region, we might have multiple nodes for that partition for HA within the region. But for cross-region, we don't want to run consensus across regions because of latency. So we design:
Within a region: for a given partition, we have a Raft group of say 3 nodes (so that if one node fails, the partition is still available in that region). But then the cross-region replication is between the leaders of each region's Raft group? That would be complex.
Alternatively, we can have a simpler design: each region has a set of storage nodes (without consensus within region) and we rely on multi-master replication across regions. But then if a node fails in a region, we lose that partition in that region? We want at least one replica per region. So we can have multiple nodes per region for the same partition (replication within region) but then how to keep them consistent? We can have a local quorum within the region for writes? But then the cross-region replication is from one of the local nodes.
Let's simplify: We have a global set of partitions. Each partition is replicated to 3 regions. In each region, we have exactly one node that is responsible for that partition (the primary for that region). But then if that node fails, the partition is unavailable in that region. So we need multiple nodes per region for the same partition? That would increase the number of replicas beyond 3.
Better: We set replication factor = 3, meaning three copies in three different regions. In each region, we have one node that holds the copy. But then if that node fails, we need to failover to another region? But that would reduce the replication factor temporarily. Alternatively, we can have two nodes in each region? Then replication factor would be 6? That's expensive.
Given that we are building a feature flag system, the data size is small (each flag is a few KB). We can afford more replicas. Let's say we have 3 regions, and each region has 2 nodes for each partition (so total 6 copies). Then we can have a local quorum within the region (2 nodes) and cross-region replication to other regions. But then we have 6 copies, and we need to decide which ones are authoritative.
Actually, we want to be able to write in any region and have the write propagate to all other regions. So we can have a multi-master setup where each region has a set of nodes that accept writes for the partitions they own. We can have a local quorum of 2 out of 3 within a region for writes? But then if the region is partitioned, we might not get quorum.
Given the complexity, let's go with a simpler design:
We have 3 regions: A, B, C.
Each region has a cluster of storage nodes (say 3 nodes) that run a Dynamo-style protocol (consistent hashing, virtual nodes, etc.) for the entire keyspace. But then the data is partitioned across all nodes in all regions? That would mean each partition is stored in multiple regions and also within a region? Actually, in Dynamo, the replication factor is N and you have a preference list of N nodes for each partition. The nodes are chosen from the ring. So we can set N=3 and ensure that the three nodes are in three different regions? That would require the ring to be split by region. But then if we have many nodes per region, we can have multiple partitions per region.
But then writes go to all N nodes? In Dynamo, writes are sent to all N nodes in the preference list, but we can have a write quorum of W and read quorum of R such that R+W > N for strong consistency. But we want eventual consistency, so we can set W=1 and R=1. That means we can write to any one node and read from any one node, but then we might get stale reads. And we have to resolve conflicts when reading (since we read from one node, we don't see all versions). Actually, in Dynamo, when reading, we read from multiple nodes (R) and then resolve conflicts. But if we set R=1, we read from one node and we might not get the latest. But we can still have conflicts when replicating between nodes.
So let's design:
We have a ring of storage nodes. Each node belongs to a region. The ring is constructed so that the tokens are distributed across regions. We set replication factor N=3, and we ensure that the N nodes for a partition are in 3 different regions. This is done by having separate token ranges per region? Or by using a datacenter-aware partitioning.
Write: client sends write to a coordinator node (any node). The coordinator sends the write to all N nodes in the preference list (which are in 3 regions). It waits for W acknowledgments (we set W=1 for high availability, so it returns after one node acknowledges). But then the other nodes might not get the write? Actually, in Dynamo, the coordinator sends to all N and waits for W. If W=1, it returns after one node writes. But then the other nodes might not have the write. That's okay because we have eventual consistency: the write will be replicated asynchronously? Actually, in Dynamo, the write is sent to all N nodes synchronously, but the coordinator doesn't wait for all. So all N nodes should eventually get the write because they are all contacted. But if one node is down, it will miss the write and then later catch up via hinted handoff or anti-entropy. So with W=1, we are accepting that the write might only be on one node temporarily. But then if that node fails, we lose the write? Not if we have hinted handoff: the coordinator that didn't get an ack from a node will store a hint and deliver later. But if the coordinator itself fails? Then the write might be lost. So to ensure durability, we need W+N-R > N? Actually, for durability we want to write to at least one node that is not the coordinator? But the coordinator is one of the N. So if we set W=1, and the coordinator is one of the N, then the write is on the coordinator and maybe others. But if the coordinator fails before replicating to others, then the write might be lost if the coordinator was the only one that got it? But the coordinator is part of the N, so if it fails, then the data is lost unless we have a replica on another node that got it. But we set W=1, so only one node might have it. So to avoid data loss, we must have W>=2? But then we reduce availability.
Given that feature flags are not critical data (we can repopulate from source of truth), maybe we accept some risk? But we want eventual consistency, so we can set W=1 and rely on the fact that the write will be replicated to other nodes eventually via anti-entropy. But if the node that got the write fails before replication, we lose that update. So we need to set W such that we have durability. Typically, for Dynamo, they set W=2 and N=3, so that even if one node fails, the data is on at least two nodes. But then if a region is down, we might not get W=2 if the two nodes are in the same region? Actually, we want the W nodes to be in different regions? Not necessarily.
We can set N=3, W=2, R=1. Then we need two nodes to acknowledge a write. If we choose the two nodes from two different regions, then we have the write in two regions. That gives cross-region durability. And reads from one node might be stale but we accept that.
But then if a region is partitioned, we might not be able to get two acks if the two acks required are in the partitioned region? Actually, the coordinator will try to send to all three and wait for 2. If one region is down, then we might only get one ack from the remaining two regions? Wait, we have three regions: if one region is down, we have two regions up. The coordinator might be in one of the up regions. The preference list has one node in each region. So if one region is down, then we have two nodes up (one in the coordinator's region and one in another). We can get two acks from those two? Yes, because the coordinator can get ack from itself (if it's one of the N) and from the other up region. So W=2 is achievable as long as at least two regions are up. That's good.
So we set:
Replication factor N=3, with each replica in a different region.
Write quorum W=2.
Read quorum R=1 (for low latency) but then we might read stale data. Alternatively, we can set R=2 to get more up-to-date reads, but that would increase latency (cross-region). We want read latency low, so we read from the local region (the coordinator can be chosen to be in the same region as the client? Actually, the client can send to any coordinator, but we can use a load balancer that sends the client to a coordinator in the same region). Then the coordinator will read from its local replica (if R=1) and return. But if we set R=1, the coordinator reads from one node (which could be itself) and returns. That node might not have the latest write if the write quorum was satisfied by two other regions? But then the read might be stale. However, we have anti-entropy that will eventually synchronize. So it's eventually consistent.
If we want to reduce staleness, we can set R=2 and have the coordinator read from two nodes (which might be in different regions) and return the latest (based on timestamp). But that increases read latency.
Given that feature flags are updated infrequently and evaluations are frequent, we can accept some staleness. So we set R=1.
Conflict Resolution during Reads:
When reading with R=1, we don't see conflicts because we only read one node. But during replication, when a node receives a write that it already has a different version for, it must resolve. We use HLC timestamps. So each write has an HLC. When replicating, if the incoming write has a higher HLC, it overwrites. If same HLC, we break ties by region ID (or node ID). This ensures deterministic resolution.
Health Monitoring:
Each node reports its health (heartbeat) to a monitoring system.
We monitor replication lag: each node tracks the last HLC it has received from each peer? Or we can have a separate process that checks the timestamp of the latest write on each replica for a sample of keys and compares.
If a node is down, we mark it as unhealthy and remove it from the ring? But we have multiple nodes per region? Actually, we have only one node per partition per region? In our design, we have N=3, so three nodes total, each in a different region. But what if we have multiple nodes in a region for the same partition? That would increase N. Let's stick with N=3, one per region. But then if a node in a region fails, that partition is unavailable in that region? Actually, if the node fails, we lose that replica. But we still have two replicas in other regions. The write quorum W=2 can still be satisfied if the two remaining regions are up. But reads from the failed region will fail. So we need to remove the failed node from the ring and assign a new node in that region? But we only have one node per region per partition. So if that node fails, we need to replace it with another node in the same region? That means we need to have spare nodes in each region. So we can have more than one node per region for the same partition? That would increase N. Alternatively, we can have a pool of nodes in each region and assign partitions to them. So if a node fails, we reassign its partitions to other nodes in the same region. That's the typical Dynamo approach: we have many nodes in each region, and the ring is shared across regions. But then the replication factor N=3 might assign three nodes in the same region? We want to avoid that. So we need to ensure that the preference list for a partition includes nodes from distinct regions. This can be done by having separate rings per region? Or by grouping nodes by region and then when building the preference list, we pick one node from each of N different regions.
We can do:
We have a set of regions. For each region, we have a set of storage nodes.
We partition the keyspace into partitions (using consistent hashing). For each partition, we assign a list of N regions (without replacement) that will store that partition. Then within each region, we pick a node (maybe randomly) to store the partition. But if a node fails, we pick another node in the same region.
So the metadata that maps partition -> list of regions is stored in a metadata service. And each region has a local mapping of partitions to nodes (which can change if nodes fail).
Evaluation Service:
The evaluation service is deployed in each region. It needs to evaluate feature flags for clients. It reads from the local feature flag store (the node in its region that holds the partition). But if that node is down, it can read from another node in the same region? But if the partition is only assigned to one node in the region, then if that node is down, the evaluation service cannot read that partition. So we need to have multiple nodes per region for the same partition? Actually, we can have the evaluation service read from any node that has the partition. But if the partition is assigned to only one node in the region, then when that node is down, the evaluation service must read from another region? That would cross region and be slow. So we want at least two nodes per region for each partition? That would increase the total number of replicas.
Alternatively, we can have the evaluation service cache the feature flags in an external cache (like Redis) that is replicated across regions? But then we have another system.
Given the complexity, let's change the design:
We want the evaluation service to be low latency and highly available. So we want it to read from a local store that is highly available. So we should have multiple storage nodes in each region for each partition. That means we set replication factor per region? Actually, we want cross-region replication for durability and locality. So we set:
Global replication factor: N (number of regions) = 3.
Within each region, we have a local replication factor of M (say 2) for high availability. So total replicas = 3 * 2 = 6.
But then the preference list for a partition would include 2 nodes in region A, 2 in region B, 2 in region C? That would be 6 nodes. But we only need one from each region for cross-region? Actually, we want to be able to read from any node in the local region. So if we have multiple nodes in the region, the evaluation service can read from any of them. And if one node fails, another in the same region can serve.
So we design:
The keyspace is partitioned into P partitions.
Each partition is assigned to 3 regions (one replica per region) but within each region, the partition is stored on M nodes (so there are M copies in each region). But wait, that would be 3*M copies. But we might not need M copies in each region if the region has many nodes and we distribute partitions across them. Actually, we want the partition to be available in the region even if some nodes fail. So we can have the partition stored on multiple nodes in the region (using a local replication factor). But then the total number of copies is more than 3.
Alternatively, we can have a two-level replication:
First, choose 3 regions (out of available regions) for the partition.
Then, within each region, choose one node to store the partition. But then if that node fails, we need to choose another node in the same region. That requires rebalancing.
We can have a metadata service that tracks for each partition: which regions and which nodes within the region. And when a node fails, we reassign the partition to another node in the same region.
But then the evaluation service in that region might have to know which node to read from. We can have a local load balancer in each region that routes read requests to one of the nodes that has the partition. Or the evaluation service can query the metadata service to find the node for a given partition. But that adds latency.
Better: the evaluation service can read from any node in its region that might have the partition? But not every node in the region has every partition. The partition is assigned to specific nodes.
We can have a consistent hashing ring per region? Actually, we can have one global ring that includes all nodes from all regions, but we want to control that the replicas are in distinct regions. This is getting complex.
Given the time, let's simplify further:
We assume that each region has a cluster of storage nodes that are identical (they all store all partitions? No, that's not scalable). We want to partition the data.
We can use a design similar to CockroachDB: we have a range-based replication. But that's too heavy.
Given that feature flags are small and we might have at most thousands of flags, we can store all flags in each region? That is, we replicate the entire dataset to each region. Then we don't need partitioning. We just have a full copy in each region. And within the region, we have multiple nodes for HA. That simplifies a lot.
So:
We have 3 regions. Each region has a full copy of the feature flag store (all flags). The store in each region is a Raft cluster of 3 nodes (for strong consistency within the region). But then we have cross-region replication. If we want multi-master, we need to allow writes in any region. So we have active-active replication between regions. We can use a multi-master replication system like MySQL with conflict resolution? Or we can use a CRDT-based store.
But if we have full copy in each region, then the data size is small (say 1MB) so we can replicate the entire dataset. We can use a log-based replication: each region's store writes updates to a log, and the logs are shipped to other regions. Conflicts can be resolved by timestamp.
So:
Each region has a cluster (say 3 nodes) that form a Raft group for the local store. Writes to the local region go through the Raft leader and are durably stored. Then these writes are asynchronously replicated to other regions via a separate process (like a change data capture). The replication is done by sending the write log entries to the other regions. The other regions apply the writes in order. But if two regions have concurrent writes, we have a conflict. We need to resolve.
We can assign a global timestamp to each write (using HLC). When a region receives a write from another region, it compares the HLC with the local version. If the incoming is newer, it overwrites. If the local is newer, it ignores? But then the write from the other region might be lost. We need to ensure that all writes are eventually applied. So we need a way to merge concurrent writes. But if we have a global total order, we don't have conflicts. But we don't have a global total order because we have multi-master.
So we need a conflict resolution policy. Since the entire flag is a blob, we can use last-write-wins based on HLC.
But note: if we use Raft within each region, then within a region the writes are ordered. But across regions, we have concurrent writes. So when replicating, we might have two writes with different HLCs. We pick the higher HLC.
To generate HLC, we can have each region's Raft leader assign timestamps that are hybrid logical clocks. The HLC includes physical time and a logical counter. When replicating, we send the HLC with the write. The receiving region compares the HLC with the local version's HLC.
But also, we must ensure that HLCs are monotonically increasing within a region? The Raft leader will assign an increasing logical clock for each entry. But when replicating to another region, that region might have a different physical time. HLC handles that by using the maximum of physical times and incrementing the logical counter if necessary.
So we can implement HLC.
Evaluation Service:
The evaluation service in each region reads from the local Raft cluster (the leader). So it gets strongly consistent reads within the region. But across regions, the data might be stale because replication is asynchronous. That's okay for eventual consistency.
The evaluation service caches the flags in memory. It can watch the Raft log for changes and update the cache. Or it can periodically poll. Since the Raft cluster can provide a notification when there's a change (like a stream of changes), we can have the evaluation service subscribe to that.
Health Monitoring:
Monitor the Raft clusters in each region (leader, followers). If a region's cluster loses quorum, then that region cannot serve writes or reads? Actually, if a Raft cluster loses quorum, it cannot make progress. So we need to detect that and perhaps failover to another region? But the evaluation service in that region might still read from the last committed entry? But if the cluster is down, it cannot read. So we need to take the region out of rotation.
Also monitor replication lag between regions. We can have a process that periodically checks the latest HLC in each region and compares.
Failover Strategy:
If a region's Raft cluster is unavailable (no leader), then we stop sending client requests to that region's evaluation services. The global load balancer will route to other regions.
For writes: if a region is unavailable, the client can write to another region. The write will go through that region's Raft and then be replicated to the down region later.
For reads: if a region is unavailable, read from another region (but higher latency). But the evaluation service in the region is down, so we don't send clients there.
But what if the entire region is down (network partition or disaster)? Then we have only two regions. We still have two copies of the data. The write quorum for the local Raft is 2 (since we have 3 nodes, we need 2 for quorum). If a region is down, we still have two regions. But within each region, we have 3 nodes. So if one region is completely down, we still have two regions with their own Raft clusters. The system can still accept writes in the two regions and replicate between them. But we must ensure that the replication between the two regions is possible. If the network partition isolates one region from the other two, then that region might accept writes and the other two accept writes. Then when the partition heals, we have conflicts between the three regions. We resolve by HLC.
So the system remains available.
Summary of Design:
Data Storage:
Each region has a Raft cluster of 3 nodes that stores the entire feature flag dataset (since it's small).
Replication between regions: asynchronous, using a log shipping mechanism. Each region's Raft leader sends its committed log entries to the leaders of other regions. The receiving region applies the entries in order, but if there's a conflict (the entry is for a key that has been updated with a higher HLC), then it might skip or overwrite? Actually, we need to apply in HLC order. But since we are shipping logs from each region, the logs are ordered within the region but not across regions. So we might receive an entry from region A with HLC=100 and then from region B with HLC=90, but we already applied a higher HLC from elsewhere? We need to buffer and sort by HLC? That's complex.
Alternative: instead of shipping logs, we can use a multi-master database that handles conflict resolution, like PostgreSQL with BDR? But we want to build our own.
We can have each region maintain a separate log. When replicating, we send the entire state? That's inefficient.
Given the small data size, we can do full state sync periodically? But then we lose real-time updates.
Better: we use a operational log with HLC. Each write gets a unique ID (HLC). When replicating, we send the write (key, value, HLC). The receiving region stores the write in a pending set and then applies in HLC order? But we need to ensure that we don't apply a write that is older than the current version. So when we receive a write, we compare its HLC with the current HLC of that key. If the received HLC is higher, we apply and update the HLC. If lower, we ignore. But what if we receive two writes out of order? We might ignore a write that is actually newer because we haven't applied an intermediate write yet? So we need to buffer writes that are not contiguous? This is like a anti-entropy with version vectors.
We can use a version vector per key? But that's heavy.
Given the small dataset, we can do:
Each region maintains a log of all writes (with HLC) that it has applied.
When replicating, we send the log since the last sync. The receiving region applies the writes in the order of HLC (which might be out of order with respect to the log order). But we can sort by HLC before applying? But then we might apply a write that is older than a write we already have? We need to check each write's HLC against the current version's HLC. So we can simply process each write in the received log: for each write, if the HLC is greater than the current HLC for that key, apply. Otherwise, skip.
But what if we receive a write with HLC=10, then another with HLC=9? We skip the second. But what if the second write is actually newer because the first write was not received yet? That cannot happen because HLC is monotonically increasing per region? Not necessarily: two regions can have concurrent writes with HLCs that are not comparable? Actually, HLC is designed so that if event A happened-before event B, then HLC(A) < HLC(B). For concurrent events, HLC might be equal or one might be higher depending on physical time and logical counters. But if we break ties by region ID, then we have a total order. So we can assume HLCs are totally ordered (by physical time, then logical counter, then region ID). So if we receive two writes, we can compare their HLCs and apply the higher one. But if we apply the higher one first, then the lower one will be skipped. That's fine.
But what if we receive a write that is higher than the current, but then later we receive an even higher one? That's okay, we apply in order as we receive.
However, we might receive a write that is higher than current, apply it, and then later receive a write that is even higher? That's possible if the replication is out of order. But we will apply the higher one when we receive it. So we don't need to buffer, just apply each write as we receive and compare with current.
But what if we receive a write that is lower than current, but that write is for a key that we haven't seen any write for yet? Then we should apply it because it's the only write? But if we have no current value, we should apply any write. So condition: if the key does not exist, apply. If exists, apply only if received HLC > current HLC.
But then if we receive a write that is older than the current, we skip. But what if that older write is actually the one that should be applied because the current write was from a different region and we want last-write-wins globally? We are using HLC as the total order, so if the current has a higher HLC, it wins. So skipping is correct.
So replication process:
Each region, periodically, contacts other regions and sends all writes (or writes since last sync) for all keys. But we can optimize by sending only the writes that the other region might not have? We can send the entire log? Since the dataset is small, we can send the entire state? But that's wasteful. We can send the writes since the last successful sync. We need to track per region the last log index or HLC we have synced to. Actually, we can track per key? That's heavy. Since the dataset is small, we can just send all writes and let the receiver filter. But that doesn't scale if we have many writes.
Alternative: we can have a global log? No.
We can have each region maintain a log of all writes (with HLC). When replicating to another region, we send the log entries that have HLC greater than the last HLC we sent to that region. But we need to track for each peer region the last HLC we sent? That's per key? No, we want to send all writes that are newer than what the peer has. But the peer might have missed some writes. We can send the entire log and let the peer apply what it needs. But that's inefficient.
Given the small dataset size (number of keys is small, but number of writes might be high if updates are frequent), we need to optimize. But feature flags are updated infrequently. So we can assume that the number of writes per day is low (maybe hundreds). So we can send all writes every time? That's acceptable.
So replication: every few seconds, each region sends to all other regions the list of all writes (key, value, HLC) that have been committed since the last replication. The receiving region applies them as described.
But then we might send the same write multiple times. We can deduplicate by storing the last HLC received from each region? Actually, we can have the receiving region acknowledge the highest HLC it has applied from the sender? That's complex.
Given the low write volume, we can just send all writes each time and the receiver will skip duplicates (by checking if the HLC is not greater than current). But if we send a write that the receiver already has with the same HLC, it will skip. That's fine.
But if we send a write that the receiver has already applied but with a lower HLC? That shouldn't happen because we only send writes that are new to the sender? Actually, we send all writes since last replication. If we replicate every 10 seconds, we send the writes in the last 10 seconds. But if the receiver already applied some of those writes from another region, then it will skip based on HLC. So it's okay.
Implementation Steps:
Set up 3 regions (AWS regions, for example).
In each region, deploy a Raft cluster of 3 nodes for the feature flag store. Use an existing Raft library (like etcd's Raft) or build a simple one. The store holds a map of feature flag ID to configuration (and HLC).
Each Raft cluster exposes a read and write API. Writes go through the leader and are appended to the log. The leader assigns an HLC to each write. The HLC is generated by the leader: it takes the current physical time and a logical counter that increments for each write in the same time unit. When receiving a write from a client, the leader generates an HLC and includes it in the log entry.
Replication between regions: a separate process (or a thread in each Raft node) that, every T seconds (e.g., 5 seconds), connects to the leaders of other regions and sends all log entries (or all writes) that have been committed since the last replication. The receiver (the leader of the remote region) applies each write by comparing HLC: if the key doesn't exist, or if the incoming HLC is greater than the current HLC for that key, then update the key and update the HLC. Otherwise, skip.
We need to be careful: the receiver might be applying writes out of order from different regions. But since we compare HLC, it should be safe.
However, we must ensure that we don't miss writes. If we only send since last replication, we might miss writes that were sent but not applied because of conflict? Actually, we send all writes that were committed on the sender. The receiver will apply only those that are newer. But what if the receiver already has a write from another region that is newer? Then it will skip. That's fine.
But what if the receiver has a write from another region that is older? Then it will apply the sender's write if it's newer. So eventually, the highest HLC wins.
Evaluation service: in each region, we deploy multiple instances behind a load balancer. The evaluation service reads from the local Raft cluster (from the leader or any follower? We can read from followers for load, but then we might read stale data. Since we have Raft, followers might be slightly behind. But we can read from the leader for strong consistency within the region? But that might overload the leader. Since feature flag reads are frequent, we can read from followers and accept slight staleness (within the region, the follower might be a few milliseconds behind). Or we can have the evaluation service watch the Raft log for changes and update its cache. That way, it always has the latest committed value in the region. But if the leader changes, we need to reconnect.
We can have the evaluation service connect to the Raft cluster via a library that handles leader election and reads from the leader? Or we can have a local caching layer like Redis that is updated by a process that watches the Raft log.
Simpler: the evaluation service makes RPC calls to the Raft cluster's read API. The Raft cluster can serve reads from the leader for strong consistency, or from followers for stale reads. We can configure to read from followers for performance. Since the replication between regions is asynchronous, the data in the region might be stale compared to other regions, but that's acceptable.
Deployment:
We need a way to deploy the Raft clusters and evaluation services in each region.
We need a global load balancer (like AWS Route53 with latency-based routing) that sends client requests to the closest region's evaluation service. But if that region is unhealthy, we need to failover to another region. We can use health checks at the load balancer.
For writes, the client can write to any evaluation service, which will forward to the local Raft cluster. But if the local region is down, the evaluation service should return an error? Or we can have the evaluation service proxy the write to another region? That would add latency. Better: the load balancer should not send write requests to an unhealthy region. So the client should write to a healthy region. We can have separate endpoints for read and write? Or the same endpoint.
We can have the evaluation service be both read and write. The load balancer sends traffic to the nearest region that is healthy. If that region is healthy, it handles both reads and writes. If it's down, the load balancer routes to another region.
But what if the client is in a region that is down, but there is a closer region that is up? The load balancer can route to that region. That might increase latency but acceptable.
Consistency Guarantees:
Within a region, reads are linearizable (if we read from the Raft leader) because Raft provides linearizable reads. But if we read from a follower, we get stale reads. We can choose to always read from the leader for strong consistency within the region. That would increase leader load but it's okay if we have few writes. Or we can use read leases to allow stale reads with bounded staleness.
Across regions, we have eventual consistency because replication is asynchronous and conflicts are resolved by last-write-wins (with HLC). So a read in one region might not see the latest write from another region until replication catches up.
Conflict Resolution Edge Cases:
If two writes happen at exactly the same HLC (unlikely but possible if physical time is the same and logical counter is same? But each region has its own HLC generation. We break ties by region ID. So we need to assign a unique region ID and include that in the HLC comparison. We can define HLC as a tuple (physical_time, logical_counter, region_id). Then we compare lexicographically.
When replicating, if we receive a write with the same HLC as the current, but different value? That means two writes with the same HLC from different regions? That can happen if two regions generate the same physical time and logical counter? But the logical counter is per region, so two regions can have the same counter value at the same physical time. Then we have a conflict with same HLC. We break tie by region ID: the write with the higher region ID wins? But then if two regions have the same physical time and same logical counter, the one with higher region ID will always win. That might be unfair. But it's deterministic.
Alternatively, we can have the HLC be globally unique by including the region ID in the physical time? No.
We can have the HLC be a 128-bit number: high 64 bits are physical time (in milliseconds), then 32 bits logical counter, then 16 bits region ID. That ensures uniqueness if we don't have more than 2^16 regions.
So when comparing HLCs, we compare as numbers. If equal, then they are truly the same? But if two regions generate the same physical time and same logical counter, then the HLC would be equal if region ID is the same? But region IDs are different. So if we include region ID, then HLCs from different regions will be different even if physical time and logical counter are the same. So we can compare HLC as a single number and the larger wins. But then if we have two writes with the same physical time and logical counter but different region IDs, the one with higher region ID will have a higher HLC number if we encode region ID in the lower bits. That's fine.
So we treat HLC as a totally ordered number.
Data Distribution:
Since we are replicating the entire dataset to each region, we don't need partitioning. But if the dataset grows large (millions of flags), we might need partitioning. But for feature flags, it's unlikely. So we assume full replication.
Evaluation Service Cache:
The evaluation service should cache the flags in memory. It can subscribe to changes from the local Raft cluster. One way: the Raft cluster can provide a watch mechanism (like etcd) that sends events when a key changes. The evaluation service can watch all keys? That might be many watches. Alternatively, we can have a process that dumps the entire state periodically and the evaluation service reloads. Since the data is small, we can have the evaluation service poll the Raft cluster every few seconds for the entire set. That's simpler.
Write Path:
Client -> Load Balancer -> Evaluation Service (in region X) -> Raft Leader in region X -> Raft log -> replicate to other regions (async).
Read Path:
Client -> Load Balancer -> Evaluation Service (in region X) -> Read from Raft Leader/Follower in region X -> return flag.
Failure Scenarios:
Region A Raft cluster loses quorum: The evaluation services in region A will fail to read from the Raft cluster. The health check fails, so load balancer stops sending traffic to region A. Writes and reads go to other regions. When region A recovers, it will sync from other regions and rejoin.
Network partition between region A and B, but both have quorum locally. Both can accept writes. There will be conflicts. When partition heals, replication will occur and conflicts resolved by HLC. Some writes from one region might be overwritten by writes from the other if their HLC is lower. That's acceptable.
Evaluation service node in a region fails: the load balancer will stop sending to that instance. Other instances in the same region continue.
Monitoring:
Replication lag: we can have a metric that shows the maximum HLC difference between regions. We can have a process that for each region, takes the maximum HLC of all keys, and compares with other regions. If the difference is above a threshold, alert.
Raft health: per region, track leader changes, commit lag.
Failover Strategy:
Automatic failover for load balancer: health checks on evaluation service endpoints. If the evaluation service cannot read from the local Raft store (or returns errors), it is marked unhealthy.
For the Raft cluster itself, if a node fails, Raft will automatically elect a new leader if a majority is available. No manual intervention needed.
If an entire region fails, we rely on the load balancer to route to other regions.
Deployment and Operations:
We need to deploy the Raft clusters in each region with at least 3 nodes across availability zones in that region for HA within the region.
We need to set up inter-region networking (VPC peering or similar) for replication.
We need to configure region IDs and ensure they are unique and ordered for tie-breaking.
Scalability:
Since we replicate the full dataset to each region, the dataset size must fit in memory of each Raft node and evaluation service. Feature flags are typically small, so this is fine.
Write throughput is limited by the Raft leader in each region. But feature flag updates are infrequent, so that's okay.
Read throughput: each evaluation service instance can handle many requests per second. We can scale horizontally by adding more evaluation service instances in each region.
Consistency Model:
Within a region, if we read from the Raft leader, we get linearizable reads (since Raft ensures that the leader has all committed entries). But if we read from a follower, we might read stale data (because the follower might not have applied the latest committed entry). We can use read leases to ensure that the leader has not changed and the follower is up-to-date? That's more complex. We can decide to always read from the leader for strong consistency within the region. But then the leader might become a bottleneck. Given that reads are more frequent than writes, we might want to allow stale reads from followers. We can accept that reads might be stale by a few milliseconds. That's acceptable for feature flags.
Across regions, we have eventual consistency with a staleness bound of the replication delay (typically seconds).
Security:
We need to secure the replication traffic between regions (TLS).
The evaluation service should authenticate clients? Not necessarily, but we might have API keys.
This is a high-level design. We can now provide a detailed plan.
But the question asks to "construct" so we need to provide a design that includes these aspects.
Let's write a structured answer.
Proposed Design:
1. Data Distribution:
Each region hosts a full replica of the feature flag dataset.
Within each region, the data is stored in a Raft cluster of 3 nodes for high availability and strong consistency within the region.
The dataset is small (feature flags are typically a few KB each), so full replication is feasible.
Replication between regions is asynchronous and multi-master: any region can accept writes.
2. Conflict Resolution:
Each write is assigned a Hybrid Logical Clock (HLC) timestamp by the Raft leader in the region where the write originates.
HLC format: (physical_time, logical_counter, region_id). Physical time in milliseconds, logical counter per leader to break ties within the same millisecond, and region_id to break ties across regions.
When replicating, a region receives writes from other regions and applies them only if the incoming HLC is greater than the current HLC for that key. If equal, the write with higher region_id wins (since HLC includes region_id, they won't be equal if region_id differs).
This provides a deterministic last-write-wins conflict resolution.
3. Health Monitoring:
Intra-region: Monitor each Raft node's health (heartbeat), replication lag within the Raft cluster (follower's last applied index vs leader's commit index), and leader stability.
Inter-region: Monitor replication lag between regions by comparing the maximum HLC across all keys in each region. If the difference exceeds a threshold (e.g., 5 seconds), generate an alert.
Evaluation service health: Monitor response times and error rates for the feature flag evaluation API.
Use a centralized monitoring system (e.g., Prometheus) with alerts.
4. Failover Strategy:
Region-level failover: Each region's evaluation services are behind a global load balancer (e.g., AWS Route53 with latency-based routing and health checks). Health checks query a local endpoint that reads from the Raft cluster. If the region's Raft cluster is healthy (has a leader and can serve reads), the region is considered healthy. If not, the load balancer routes traffic to other healthy regions.
Within a region: Raft automatically handles node failures. If a node fails, Raft continues as long as a majority (2 out of 3) are alive. If the leader fails, a new leader is elected. The evaluation services continue to read from the new leader.
If an entire region fails (all nodes or network partition), the load balancer will mark the region unhealthy and route all traffic to other regions. Writes and reads will be served by the remaining regions. The failed region will catch up via replication when it recovers.
For the Raft clusters: if a region loses quorum (only 1 node alive), the region becomes read-only? Actually, without quorum, the cluster cannot make progress. So the region will be unable to serve writes or reads (if we require linearizable reads from leader). We mark the region as unhealthy.
5. Evaluation Service:
Stateless service that evaluates feature flags for client requests.
It reads the latest flags from the local Raft cluster. To reduce load, it caches flags in memory and refreshes periodically (e.g., every 30 seconds) or via watching the Raft log for changes.
The service is deployed in multiple instances per region behind a local load balancer. The global load balancer routes clients to the nearest region.
6. Replication Mechanism:
Each region's Raft leader periodically (every 5 seconds) connects to the leaders of other regions and sends all log entries (writes) that have been committed since the last replication.
The receiving leader applies each write by comparing HLC as described.
To avoid sending the entire log every time, we can track the last replicated HLC per remote region? But since the dataset is small and writes are infrequent, we send all writes each time and let the receiver deduplicate by HLC.
Alternatively, we can send only writes with HLC greater than the last HLC we sent to that region. We need to store per peer region the last sent HLC? But that's per key? Actually, we can send all writes and the receiver will apply only those that are newer. But we might resend old writes that the receiver already skipped? That's okay.
7. Write and Read Paths:
Write:
Client sends a write request to the evaluation service in a region.
Evaluation service forwards to the local Raft leader.
Raft leader appends the write to its log, assigns HLC, and replicates to its followers.
Once committed, the leader responds to the evaluation service, which responds to client.
Asynchronously, the leader ships the write to other regions.
Read:
Client sends a read request to the evaluation service.
Evaluation service reads from the local Raft cluster (leader or follower). For strong consistency, it reads from the leader; for lower latency, it can read from a follower with possible staleness. We choose to read from followers for performance, and accept staleness of up to the replication delay within the region (typically milliseconds) plus inter-region delay (seconds). Typically, feature flag updates are not time-critical, so this is acceptable.
Evaluation service returns the flag value.
8. Deployment:
Deploy Raft clusters in each region across multiple availability zones.
Deploy evaluation service instances in each region behind a local load balancer.
Set up global load balancer with health checks pointing to the evaluation service's health endpoint.
Configure region IDs and ensure they are unique and comparable (e.g., alphabetical order or numerical).
Set up secure communication between regions (TLS, authentication).
9. Limitations and Future Improvements:
The design assumes the entire dataset fits in memory. If the dataset grows very large, we would need to partition the data. But for feature flags, this is unlikely.
Conflict resolution is last-write-wins, which may discard concurrent updates. If feature flag configurations are complex (e.g., rules with multiple conditions), we might need application-specific merge functions. This design can be extended by storing the configuration as a CRDT.
Replication lag may cause stale reads in distant regions. We can reduce this by increasing replication frequency or using a more synchronous approach (at the cost of availability).
This design provides eventual consistency with low-latency reads, high availability, and automatic failover.
Remote Feature Flag Evaluation Network with Eventual Consistency
1. Architectural Overview
The system consists of regionally deployed evaluation services backed by multi-master replicated feature flag stores. Each region holds a full copy of the feature flag dataset, enabling low-latency reads. Writes can originate from any region and propagate asynchronously. Conflicts are resolved via Hybrid Logical Clocks (HLC) with last-write-wins semantics.
Key Components:
Feature Flag Store (per region): Raft cluster (3 nodes) for strong consistency within the region.
Evaluation Service (per region): Stateless service that reads from the local store and caches results.
Replication Engine: Asynchronous log shipping between regional Raft leaders.
Global Load Balancer: Routes client requests to the nearest healthy region.
Monitoring Stack: Tracks health, replication lag, and performance.
2. Data Distribution & Storage
2.1 Replication Model
Full Replication: Each region stores the entire feature flag dataset (suitable for typical flag counts ≤ 10,000).
The evaluation service caches the flags in memory and refreshes periodically (e.g., every 30 seconds) or upon notification (if we implement watch).
Health monitoring:
Monitor each Raft node: is it alive? Is it the leader? Replication lag within the Raft cluster (follower's commit index vs leader).
Monitor inter-region replication: for each region pair, track the timestamp of the last received write and compare with the local last committed timestamp. If the difference is too large, alert.
Monitor evaluation services: response time, error rate.
Use a monitoring system like Prometheus and Grafana.
Failover:
If a region's Raft cluster loses quorum (less than 2 nodes up), then that region cannot accept writes or reads (if we require linearizable reads from leader, but we might allow stale reads from followers? But if the leader is down, we cannot read from leader. We could read from a follower, but the follower might not have the latest data if the leader went down before replicating. But since we use Raft, if the leader steps down, a new leader is elected from the followers that have the latest log. So as long as we have a majority of nodes (2 out of 3) alive, we have a leader. If we have only 1 node alive, we cannot elect a leader. So we need at least 2 nodes alive in the region to serve reads (from the new leader). If only 1 node is alive, that node cannot be leader. So we cannot serve reads? Actually, if we allow reads from followers, then even with one node alive, we can read from that follower? But that node might be outdated. But we can still read from it. However, if the region has only one node alive, then we have lost 2 nodes, which is a major failure. We might want to take the region out of rotation.
So we define: a region is healthy if it has a Raft leader (i.e., quorum of nodes alive). The evaluation services in that region will be marked as healthy only if they can read from the Raft cluster (by pinging the leader). The global load balancer will only route traffic to regions with healthy evaluation services.
For writes: if a region is unhealthy, writes are sent to other healthy regions. The replication will eventually sync to the unhealthy region when it recovers.
Conflict resolution: as described, using HLC with tie-breaking by region ID.