We are going to design a feature flag SDK that supports:
Server-Side Rendering (SSR) with defaults.
Hydration safety (avoiding mismatch between server and client).
Analytics beacons (tracking feature flag evaluations).
We assume the SDK will be used in a React-like environment (since hydration is mentioned) but the principles can be adapted.
The SDK should have:
A way to define feature flags and their possible values (could be boolean or more complex).
A mechanism to evaluate flags on the server and send the evaluated state to the client.
A mechanism to re-evaluate flags on the client if needed (for dynamic flags) but with hydration safety.
Steps:
Initialization:
On the server: we initialize the SDK with a set of flags (or a way to fetch them) and evaluate the flags for the current request.
On the client: we initialize the SDK with the server-provided flags (to avoid hydration mismatch) and then optionally re-evaluate if we have real-time updates.
Server-Side Rendering:
During SSR, we evaluate the flags and store the result in a way that can be serialized and sent to the client.
We must be cautious about the data we send (avoid sending sensitive data or too much data).
Hydration Safety:
The client must be initialized with the same flag values that were rendered on the server.
We can embed the server-evaluated flags in the HTML (e.g., in a script tag) and then the client SDK reads that and uses it as the initial state.
After hydration, the client may re-evaluate flags (if we support dynamic updates) but we must not change the flags that were rendered on the server until we are sure the client is hydrated and ready.
Analytics Beacons:
Every time a flag is evaluated, we may want to track that event (for analytics).
We should have a way to send these events to an analytics service (like sending a beacon or using an analytics SDK).
We must consider that during SSR we might not want to send analytics (or we might want to queue them and send from the client) because the server doesn't have the same context (like user session) or we don't want to affect performance.
Let's design the API:
We'll have a FeatureFlagSDK class that can be instantiated with a configuration.
Configuration options:
flags: an object defining the flags (or a function that returns them). Alternatively, we might have a way to fetch flags from a remote service.
evaluationMethod: synchronous or asynchronous? For SSR we might want synchronous evaluation (so we can render immediately) but for client we might want async (to not block). However, for hydration safety we need the server state to be available synchronously on the client? Actually, we can have:
On server: we evaluate synchronously and then serialize the result.
On client: we start with the serialized state (synchronous) and then if we have a real-time update mechanism, we can update asynchronously.
analytics: an object with an enabled flag and a send function (or endpoint) to send events.
We might have two main modes:
server: when running on the server, we evaluate and provide the state for serialization.
client: when running on the client, we rehydrate and then optionally update.
However, we want the same code to run on both? So we might have:
const sdk = new FeatureFlagSDK(config);
if (isServer) {
const state = sdk.evaluateAll(); // synchronous evaluation
// then we can embed state in HTML
} else {
// on client, we rehydrate with the state from the server
sdk.rehydrate(serverState);
// then we might start listening for updates (if we have a real-time mechanism)
}
But what about dynamic flags that might change during the same session? We might want to update the client without a full page reload.
We can also have:
sdk.on('update', (flagKey, newValue) => { ... });
But for hydration safety, we must ensure that the initial render on the client matches the server. So we should not update until after hydration.
Alternatively, we can have:
The server sends the state at the time of rendering.
The client uses that state for the initial render (so that the HTML matches).
Then, after hydration, the client may fetch the latest state (if we want real-time) and update the components that use the flags.
This means we have two sources of truth for a short time: the server state and the client's fetched state. We must be cautious about when we update.
Design:
We have a Flag class that holds:
key
value (evaluated value)
maybe metadata (like variation, reason, etc.)
The SDK holds a map of flags.
We have an evaluate method that given a flag key and maybe context (user, etc.) returns the value.
For SSR, we might evaluate all flags at once and then serialize the entire map.
For hydration, we set the initial state of the SDK to the server state.
For analytics, we can have:
A method track that sends an event for a flag evaluation.
We can track every evaluation? That might be too many. Alternatively, we can track only when the flag value changes? Or when a flag is evaluated for the first time in a session?
Let's assume we want to track every evaluation (for debugging and analytics). But note: if we evaluate the same flag multiple times in the same request, we might not want to track multiple times? We can decide to track only once per flag per request? Or track every time? It depends.
We can have an option trackEvaluations: boolean and then when evaluating, if tracking is enabled, we send an event.
But on the server, we might not want to send events (because we don't have the user context, or we want to batch). So we can have:
On server: we can collect the events and send them at the end of the request? But then we don't have the response body yet? We can send them as part of the response? Not ideal.
Alternatively, we can have:
The SDK on the server does not send analytics by default. We can have a separate mechanism to send events from the server (like logging) or we can queue them and then the client sends them? But then we lose the server-side evaluations.
Since the problem says "analytics beacons", it might be that we want to send them from the client. So we can:
Track on the client only? But then we lose the server evaluations.
We might want to track both? But then we have to be careful not to double count.
Let's assume:
We want to track every evaluation on the client (after hydration) and also track the initial server evaluation? Maybe we can track the server evaluation as a separate event (with a flag fromServer: true). But then the client will also evaluate and track again.
Alternatively, we can have:
The server evaluation is only for rendering and we don't track it? Then the client, after hydration, will evaluate and track.
Let's write the code accordingly.
However, note: the problem says "SSR defaults". We are not using defaults? We are evaluating the flags on the server and sending the evaluated state. So the client doesn't need defaults? The client uses the server state as the initial state.
But what if a flag is not defined on the server? We throw an error. We might want to have a default value for undefined flags? We can have a defaultValue in the flag definition? But then on the server, if the flag is not defined, we throw? We can change:
In ServerFeatureFlagSDK:
code
evaluate(flagKey, context) {
const definition = this.flags[flagKey];
if (!definition) {
return this.config.defaultValue; // or throw?
}
...
}
But then we are not tracking analytics for default values? We might want to track that we used a default.
Alternatively, we can require that all flags are defined.
Given the time, we'll leave it as throwing an error.
Let's code.
We'll write the base SDK first.
Note: We are using ES6 classes and modern JavaScript.
We'll assume the environment supports ES6.
Let's write the code.
I'll design a feature flag SDK specification that addresses SSR defaults, hydration safety, and analytics beacons. Here's a comprehensive specification:
Lazy Flag Loading: Load flags on-demand for non-critical features
Cache Invalidation: Smart cache with TTL and context-based keys
Bundle Splitting: Separate SDK for client vs server
Memoization: Cache evaluations with same context
Request Deduplication: Debounce remote flag fetches
11. Security Considerations
Server-side only flags: Never expose admin flags to client
Context sanitization: Remove sensitive data from context before logging
Rate limiting: Prevent flag evaluation abuse
CSP compliance: Ensure beacon sending complies with Content Security Policy
PII redaction: Automatically redact sensitive fields from analytics
12. Testing Strategy
typescript
// Mock implementations for testing
class MockAnalyticsSender implements AnalyticsSender {
private events: FlagAnalyticsEvent[] = [];
track(event: FlagAnalyticsEvent) {
this.events.push(event);
}
getEvents() { return this.events; }
clear() { this.events = []; }
}
// SSR hydration test
test('hydration safety - no mismatch', async () => {
const serverFlags = await sdk.evaluateForSSR(serverContext);
const clientSDK = new FeatureFlagClientSDK(config, serverFlags.flags);
expect(clientSDK.validateHydration(serverFlags.flags)).toBe(true);
});
Key Features Summary
SSR Defaults: Server evaluates flags and embeds results in HTML
Hydration Safety:
Content hash validation
Deferred updates during hydration
Mismatch detection and reporting
Analytics Beacons:
Batched event sending
sendBeacon API with fetch fallback
Impression and evaluation tracking
Context-aware metadata
Flexible Deployment: Supports static, remote, and hybrid flag sources
React Integration: Provider pattern with hooks for type-safe usage
Performance: Caching, lazy loading, and request deduplication
Observability: Error boundaries, monitoring integration, and debug modes
This specification provides a robust foundation for a feature flag SDK that safely handles SSR/hydration while capturing comprehensive analytics data.
But what if the flag is dynamic and changes on the client? We want to track the change.
We can design:
The SDK tracks an event every time a flag is evaluated and the value is different from the last tracked value for that flag in the same session? Or we track every evaluation and let the analytics backend dedupe?
Given the complexity, let's keep it simple:
We have an option analytics with enabled and a send function.
When a flag is evaluated (via evaluate or evaluateAll), if analytics is enabled, we send an event for that flag with:
{ flag: key, value: value, timestamp: ..., context: ... }
We can also have a way to batch events? But for beacons, we might want to send immediately.
However, on the server, we might not want to send beacons because the server might be headless. So we can have:
The SDK on the server, when evaluating, does not send analytics by default? Or we can have a separate ServerAnalytics that collects and then we send at the end of the request? But then we are mixing concerns.
Since the requirement is for an SDK that supports SSR and hydration, we can assume:
The server part is only for rendering and the client part is for interactivity and analytics.
But the problem says "analytics beacons", which are typically sent from the client.
So let's decide:
The server will not send analytics. Instead, the server will provide the initial state and then the client will evaluate and send analytics.
But wait: what if the server evaluation is different from the client? Then we are tracking only the client evaluation.
We want to track what the user actually sees? Then the client evaluation is what matters because that's what the user interacts with.
However, for SSR, the user sees the server-rendered content. But then the client might update and change. We want to track the initial view? We can track the server evaluation as an event too? But then we are tracking twice for the same user.
Let's change:
We track on the client only, but we also want to track the fact that the user saw the server-rendered version? We can have a separate event for "initialRender" that includes all the flags? That might be too heavy.
Alternatively, we can have:
The client, after hydration, will evaluate all the flags again and then we can compare with the server state. If there's a difference, we might send an event about the mismatch? But that's for monitoring, not for user analytics.
Given the scope, let's stick to:
The SDK on the client will track every evaluation (every time evaluate is called) and send an event. But then we might track the same flag multiple times in the same page view.
We can have:
A flag trackImpressions: boolean that when true, we track every time a flag is evaluated (for the first time in a component mount?).
This is getting complex.
Let's simplify the requirement:
We want to support analytics beacons. We'll assume that the user of the SDK will decide when to track. So we can provide:
code
sdk.track(flagKey, value, [extra]);
and then the user can call this when they want to track an impression (like when a component mounts and uses a flag). But then we are putting the burden on the user.
Alternatively, we can have:
code
const flagValue = sdk.getFlag('flag-key');
// and then the SDK automatically tracks? Not always, because the user might not want to track every evaluation.
But then we are not providing an out-of-the-box analytics solution.
Given the time, let's design:
The SDK will have an internal event system for flag evaluations.
If analytics.enabled is true, then by default we send an event for every evaluation (using the analytics.send function).
We can also allow the user to opt-out of automatic tracking per flag? Not in the initial version.
However, we don't want to track on the server. So:
On the server, even if analytics.enabled is true, we don't send? Or we can have analytics.send be a no-op on the server? But then the server might have a different send function (like logging to console).
We can have:
The analytics config has a send function that is called with the event.
On the server, we can set analytics.send to a function that collects events and then we can do something with them (like log them) but not send beacons.
But the requirement says "analytics beacons", which are typically sent via navigator.sendBeacon on the client.
So let's assume:
The analytics.send function is only called on the client.
How do we know if we are on the client? The SDK can be instantiated differently on server and client? Or we can have a flag isServer in the config.
We can do:
const sdk = new FeatureFlagSDK({
flags: ...,
analytics: {
enabled: true,
send: (event) => {
// on client, this uses sendBeacon, on server, maybe just logs?
}
},
isServer: true // or false
});
But then we are duplicating the configuration.
Alternatively, we can have two different entry points: createServerSDK and createClientSDK.
Let's have:
On server: we use FeatureFlagSDK with server: true and it doesn't send analytics (or sends to a different place).
On client: we use FeatureFlagSDK with server: false and it sends beacons.
evaluate(flagKey, context) {
// ... evaluate and get value
if (this.analyticsEnabled && !this.isServer) {
this.sendAnalytics(flagKey, value, context);
}
return value;
}
sendAnalytics(flagKey, value, context) {
const event = { flag: flagKey, value, context, timestamp: Date.now() };
this.config.analytics.send(event);
}
}
But note: on the server, we might still want to collect analytics events? Maybe not, because we don't have the user context and we don't want to send from the server.
So we can skip sending on the server.
Hydration safety:
We need to make sure that when the client starts, it uses the same flag values as the server.
We can do:
On server: after evaluating all flags, we serialize the state (the map of flags) and embed in the HTML.
On client: we create the SDK and then call rehydrate(serverState) which sets the internal flag map to the serverState.
But what if the client also has a way to fetch the latest flags? We might want to update the flags after hydration.
We can have:
After rehydration, we can optionally fetch the latest flags (if we have a url for fetching) and then update the flags.
But then we have to update the components that use the flags.
We can use React context or a global store? The SDK itself can be a store and provide a subscription mechanism.
Let's design the SDK as a store:
It has a getFlag(flagKey) method that returns the current value.
It has a subscribe(callback) that calls the callback when any flag changes.
Then, on the client:
We rehydrate with the server state, so the initial getFlag returns the server state.
Then we can fetch the latest state and update the store, which will trigger subscriptions.
But then we have to be cautious: the server-rendered content was based on the server state. If we update the flags immediately after hydration, the content might change and cause a mismatch? Actually, the hydration has already happened, so the DOM is already in place. If we update the flags and the components re-render, that's okay because it's after hydration.
However, we might want to avoid updating if the server state and the client-fetched state are the same? We can compare and only update if different.
But note: the server state might be stale (if the flag changed between the server render and the client fetch). We want the client to have the latest.
So:
Hydration: set the state to the server state.
Then, fetch the latest state and update the store (even if same? we can skip if same to avoid unnecessary re-renders).
But what about the initial client evaluation? We don't want to evaluate again on the client for the initial render because we already have the server state. So we don't call evaluate again for the initial render. We just use the server state.
However, if we have a flag that depends on context (like user) and the context might be different on the client? But the server had the same context? We assume the context is the same (like user session is passed from the server). So the server state should be the same as the client would evaluate.
But if we have real-time updates, the flag might change. So we want to update.
Steps for client:
Rehydrate with server state.
Optionally, fetch the latest state (from a remote flags service) and update.
We can have:
sdk.startRealtimeUpdates(); // this might set up a WebSocket or polling to update flags.
But then we have to merge the server state with the fetched state? We can just replace the entire state.
However, we must be cautious: the server state might have flags that are not in the fetched state? We can merge.
Let's assume the fetched state is the complete set of flags (or at least the ones we care about). We can replace the entire map.
But what if we have flags that are only on the server? We don't want to lose them.
Alternatively, we can have:
The server state is the initial state.
The fetched state is an update that may add, remove, or change flags.
We can do:
this.flags = new Map(serverState); // then when we fetch, we update the map with the new values.
But then we have to decide: do we want to remove flags that are not in the fetched state? Probably not, because the server might have sent flags that are not in the fetched state (maybe because the fetched state is only a subset). So we should merge.
We can have:
updateFetchedState(fetchedState) {
for (const [key, value] of Object.entries(fetchedState)) {
this.flags.set(key, value);
}
// note: we don't remove flags that are not in fetchedState.
}
But then if a flag is removed on the server, we might still have the old value? We need a way to know if a flag is removed. The fetched state might not include removed flags? Then we keep the old value.
Alternatively, we can have the fetched state be the complete state and we replace the entire map.
Since we are in control of the flag service, we can decide that the fetched state is the complete state. Then we do:
this.flags = new Map(Object.entries(fetchedState));
But then we lose any flags that were only on the server and not in the fetched state? That might be acceptable if the fetched state is the source of truth for the client.
However, the server might have sent additional flags that are not in the fetched state because they are static and we don't want to fetch them again? We can have:
The server state includes all flags (static and dynamic) and the fetched state only includes dynamic flags? Then we don't want to replace the entire map.
So we need a way to merge:
We can have two sets: static flags (from server) and dynamic flags (from fetched). But then we have to know which is which.
Alternatively, we can have the fetched state be the complete state (including static) and then we replace the entire map. Then we don't need to send static flags from the server? But then the initial render would have to wait for the fetch? That defeats the purpose of SSR.
So:
The server sends the complete state (so we can render immediately).
Then we fetch the complete state again (which might be the same or updated) and update.
This way, we don't have to worry about static vs dynamic.
But then we are fetching the same static flags again? We can have the server send a version and the client fetches only if the version changed? That's an optimization.
Given the complexity, let's stick to:
The server sends the complete state (all flags) and the client uses that for initial render.
The client then fetches the complete state (from the same source) and updates the entire state.
This way, we don't have to worry about merging.
But note: the server and client might have different contexts (like user) and the flags might be different. We assume the context is the same (passed from server to client).
// Evaluate a single flag. This will also track analytics if enabled and on client.
evaluate(flagKey, context = {}) {
// Get the flag definition from the config (or from a remote fetch? We assume the config has all flag definitions or we have a way to get them)
const flagDefinition = this.config.flags[flagKey];
if (!flagDefinition) {
throw new Error(`Flag ${flagKey} not found`);
}
// Evaluate based on the definition and context.
const value = this.evaluateFlag(flagDefinition, context);
// Track analytics if enabled and on client.
if (this.analyticsEnabled && !this.isServer) {
this.sendAnalytics(flagKey, value, context);
}
return value;
}
evaluateFlag(flagDefinition, context) {
// This is a simple implementation. We assume flagDefinition has a `evaluate` function or we have rules.
// For simplicity, let's assume flagDefinition is an object with a `value` or a function that returns a value.
if (typeof flagDefinition === 'function') {
return flagDefinition(context);
}
return flagDefinition.value;
}
// Evaluate all flags and return a map of flagKey -> value.
evaluateAll(context = {}) {
const result = {};
for (const [key, definition] of Object.entries(this.config.flags)) {
result[key] = this.evaluate(key, context);
}
return result;
}
// Rehydrate: set the state from the server.
rehydrate(serverState) {
// serverState is an object: { flagKey: value, ... }
this.flags = new Map(Object.entries(serverState));
// We don't track analytics for rehydrated state because it was already tracked on the server? But we don't track on server.
// Actually, we don't track on server, so we haven't tracked the server state. But we don't want to track the rehydrated state as new evaluations.
// So we just set the state without tracking.
this.notifySubscribers();
}
// Start realtime updates: fetch the latest state and update.
async startRealtimeUpdates(pollInterval = 60000) {
// We can set up an interval to fetch the latest state.
setInterval(async () => {
try {
const latestState = await this.fetchLatestState();
this.updateState(latestState);
} catch (error) {
console.error('Failed to fetch latest flag state:', error);
}
}, pollInterval);
}
fetchLatestState() {
// We assume there's an endpoint that returns the complete state.
return fetch(this.config.flagsEndpoint).then(res => res.json());
}
updateState(newState) {
// newState is an object: { flagKey: value, ... }
// We replace the entire state.
const oldState = Object.fromEntries(this.flags);
this.flags = new Map(Object.entries(newState));
// Notify subscribers of changes (if any flag changed)
for (const key of newState.keys()) {
if (oldState[key] !== newState[key]) {
this.notifySubscribers(key, newState[key], oldState[key]);
}
}
}
// Get the current value of a flag (without re-evaluating). This uses the stored state.
getFlag(flagKey) {
return this.flags.get(flagKey);
}
// Subscribe to changes of any flag or a specific flag.
subscribe(callback, flagKey = null) {
this.subscribers.push({ callback, flagKey });
// Return unsubscribe function
return () => {
this.subscribers = this.subscribers.filter(sub => sub.callback !== callback);
};
}
notifySubscribers(flagKey = null, newValue = null, oldValue = null) {
for (const sub of this.subscribers) {
if (sub.flagKey === null || sub.flagKey === flagKey) {
sub.callback(flagKey, newValue, oldValue);
}
}
}
sendAnalytics(flagKey, value, context) {
const event = {
flag: flagKey,
value,
context,
timestamp: Date.now(),
// maybe more?
};
this.config.analytics.send(event);
}
}
Usage in React:
We can create a React context and a provider that uses this SDK.
However, note that the SDK is a singleton? We might want one instance per request (on server) and one per window (on client).
We can create the SDK instance in the provider and then provide the instance via context.
But then we have to make sure that on the server, we create a new instance for each request.
We can do:
// In the React app:
const FlagContext = React.createContext(null);
React.useEffect(() => {
// On client, we create the SDK and rehydrate with serverState, then start realtime updates.
const clientSDK = new FeatureFlagSDK({
...config,
isServer: false,
});
clientSDK.rehydrate(serverState);
if (config.flagsEndpoint) {
clientSDK.startRealtimeUpdates();
}
setSdk(clientSDK);
// Cleanup?
return () => {
// stop realtime updates? We don't have a stop method.
};
}, []);
if (!sdk) {
// During hydration, we don't have the client SDK yet, but we have the server state.
// We can create a synchronous version that just returns the server state? But we want to use the same SDK instance.
// Alternatively, we can render the children with a temporary SDK that uses the server state?
// But then we might have two SDK instances? We want to avoid that.
// We can create the SDK synchronously on the client with the server state and then later start realtime updates?
// But then we are creating the SDK in the render phase? That's not allowed because it might have side effects.
// We can do:
// let sdkRef = useRef(null);
// if (!sdkRef.current) {
// sdkRef.current = new FeatureFlagSDK({ ...config, isServer: false });
// sdkRef.current.rehydrate(serverState);
// }
// setSdk(sdkRef.current);
// But then we are creating the SDK during render? That's okay if we don't do side effects? The constructor is a side effect? We are just creating an object.
// Alternatively, we can use useMemo to create the SDK once:
const sdkInstance = React.useMemo(() => {
const sdk = new FeatureFlagSDK({
...config,
isServer: false,
});
sdk.rehydrate(serverState);
return sdk;
}, [config, serverState]);
// Then we start realtime updates in an effect.
React.useEffect(() => {
if (config.flagsEndpoint) {
sdkInstance.startRealtimeUpdates();
}
}, [sdkInstance, config.flagsEndpoint]);
return (
<FlagContext.Provider value={sdkInstance}>
{children}
</FlagContext.Provider>
);
}
return (
<FlagContext.Provider value={sdk}>
{children}
</FlagContext.Provider>
);
// We can also subscribe to flag changes?
// But if we use getFlag, we won't re-render when the flag changes.
// We can use a custom hook that subscribes:
function useFlag(flagKey) {
const sdk = React.useContext(FlagContext);
const [value, setValue] = React.useState(() => sdk.getFlag(flagKey));
React.useEffect(() => {
return sdk.subscribe((changedFlagKey, newValue) => {
if (changedFlagKey === flagKey) {
setValue(newValue);
}
});
}, [sdk, flagKey]);
return value;
}
}
Server-side:
On the server, we create an instance of FeatureFlagSDK with isServer: true and then evaluate the flags and pass the state to the client.
We can do:
// In the server-side rendering code:
const sdk = new FeatureFlagSDK({
flags: ...,
isServer: true,
analytics: { enabled: false } // or we can have a separate server analytics
});
const flagState = sdk.evaluateAll(context); // context might include user, etc.
Then we pass flagState to the client as a prop or via a script tag.
Analytics considerations:
We decided that the client will send analytics for every evaluation. But note: the evaluate method is called by the user code (or by our React hook) every time the component renders? That would be too many.
We should track only when the flag is evaluated and the value is used in a way that we consider an impression? But that's up to the user.
Alternatively, we can track only when the flag value changes? But then we miss the first evaluation.
We can change:
The evaluate method will track only if the value is different from the last tracked value for that flag? But then we need to store the last tracked value.
Let's change:
In the SDK, we store:
code
this.lastTrackedValue = new Map();
Then in evaluate:
code
const value = ...;
if (this.analyticsEnabled && !this.isServer) {
const lastTracked = this.lastTrackedValue.get(flagKey);
if (lastTracked !== value) {
this.sendAnalytics(flagKey, value, context);
this.lastTrackedValue.set(flagKey, value);
}
}
This way we track only when the value changes.
But what about the initial evaluation? We haven't tracked it, so we will track it when it changes? But if the flag never changes, we never track? We want to track the initial impression.
We can track every evaluation the first time we see a flag? But then if the flag changes, we track again.
Alternatively, we can track every time the flag is evaluated and the value is different from the last evaluated value (not tracked). But then we might track multiple times in the same render if the same flag is evaluated multiple times? We want to track only once per value per session?
Given the complexity, let's stick to tracking every evaluation (without deduplication) and let the user decide when to call evaluate? But then if a component calls evaluate on every render, we get many events.
We can change the React hook to only evaluate once? But then if the flag changes, we want to re-evaluate and track again.
Actually, the React hook useFlag will re-evaluate (by getting the current value from the SDK) every time the SDK notifies a change. So if the flag changes, we will get a new value and then we can track.
But note: the getFlag method just returns the stored value, it doesn't re-evaluate. So we are not tracking on every render, only when the value changes (because the hook only updates when the value changes).
So in the React hook:
const value = sdk.getFlag(flagKey); // this returns the current stored value.
And when the SDK updates (because of realtime update), it notifies and the hook re-renders with the new value.
But then we are not tracking the initial evaluation? Because the initial evaluation was done on the server (or on the client when we rehydrated) and we don't call evaluate on the client for the initial value.
We want to track the initial value? We can have:
In the rehydrate method, we can set the initial values and then track them? But then we are tracking the server state on the client, which is the same as what the user saw.
We can do:
rehydrate(serverState) {
// For each flag, we set the value and then if analytics is enabled, we track the initial value?
for (const [key, value] of Object.entries(serverState)) {
this.flags.set(key, value);
if (this.analyticsEnabled && !this.isServer) {
this.sendAnalytics(key, value, { fromRehydrate: true });
}
}
}
But then we are tracking the initial state as an impression. That might be what we want.
However, note: the server might have evaluated the flag and we are tracking again on the client? We are not tracking on the server, so we only track on the client. And we track the initial state (which is the same as the server) and then if the flag changes, we track again.
That seems acceptable.
Summary:
We have an SDK that can be used on server and client.
On server: we evaluate flags and produce a state object. We do not send analytics.
On client: we rehydrate with the server state and then track the initial state (if analytics enabled). Then we can start realtime updates to get the latest state and update the store.
We track each time a flag's value changes (including the initial rehydrate) by sending an analytics event.
We have a subscription mechanism so that React components can re-render when flags change.
Edge cases:
What if the server state and the fetched state are different? We update and track the change.
What if the flag evaluation depends on context that might change on the client (like user location) and the server had a different context? We assume the context is the same because it's passed from the server. But if the client has a different context (like the user changes), then the flag might change and we will update.
We are not evaluating flags on the client with context? We are just storing the value from the server and then from the fetched state. We assume the fetched state is already evaluated for the current context? Or do we need to re-evaluate on the client?
We have two options:
Option 1: The server and the fetched state are already evaluated for the current context (the same context). Then we just store the value.
Option 2: We send flag definitions and context to the client and the client evaluates? But then we might have a mismatch because the server and client might have different evaluation logic? We want to avoid that.
So we prefer Option 1: the server and the fetched state are the evaluated values for the current context.
But then if the context changes (like the user changes), we need to re-evaluate. We don't have the flag definitions on the client? We do, because we passed the config. But then we might have a mismatch if the evaluation logic changes between server and client? We are using the same SDK code, so it should be the same.
Alternatively, we can have:
The server sends the evaluated state for the current context.
The client, if the context changes, can re-evaluate the flags with the new context? But then we need the flag definitions and the evaluation logic on the client.
We already have the flag definitions in the config, so we can re-evaluate on the client if the context changes.
But then we have to decide: do we want to re-evaluate on the client when the context changes? Or do we want to fetch a new state from the server?
If we have realtime updates, we are fetching the entire state from the server. That state is evaluated for the current context (which might be the same as the client's context). So we don't need to re-evaluate locally.
However, if the context changes (e.g., user logs out) and we don't have realtime updates, we might want to re-evaluate with the new context.
We can have:
The SDK has a method setContext(context) that re-evaluates all flags with the new context and updates the state.
But then we are evaluating on the client, and we might have a different result than if we had fetched from the server? But we are using the same evaluation logic, so it should be the same.
However, if the flag definitions have changed on the server (new version) then the client would be using old definitions? We don't have a way to update the definitions without fetching.
So:
We have the flag definitions in the config (which is passed from the server). If the definitions change, we need to update the config? We can have the fetched state include the definitions? That would be heavy.
Given the complexity, let's stick to:
The server sends the evaluated state and the client uses that as the source of truth.
The client does not re-evaluate based on context changes. Instead, when the context changes, we might want to fetch a new state from the server? But then we need to send the new context to the server.
We can have:
The fetchLatestState function sends the current context (like user ID) to the server, and the server returns the evaluated state for that context.
Then, when the context changes, we call fetchLatestState again? But we are already polling? We can also have a method to manually refresh.
We can design:
The SDK has a refresh(context) method that fetches the latest state for the given context and updates.
But then we are mixing the context that was used on the server and the context on the client? We assume the context is the same.
Since this is getting very complex, we will limit the scope:
The SDK does not handle context changes on the client. The context is fixed at the time of server render and client rehydrate. If the context changes (e.g., user logs in), the application should re-render the entire app (or at least the part that uses flags) with a new server state? That would require a full page reload or a client-side navigation that does a new server render?
Alternatively, we can have:
The client SDK can be given a new context and then re-evaluate the flags with the new context (using the same definitions). But then we are not getting the latest definitions from the server.
We can have:
The server sends the flag definitions (or the entire config) and the client uses that to evaluate. Then when the context changes, we re-evaluate locally.
But then we are not getting realtime updates for flag definition changes? We can have the fetched state include the definitions? That would be a big payload.
Given the time, we will assume:
The flag definitions are static and known at build time? Or they are passed from the server and we don't expect them to change without a deploy.
The context is provided at the time of server render and then passed to the client. If the context changes (like user logs in), we do a full page reload (or a client-side navigation that does a new server render) so that we get a new server state.
This is a common pattern in SSR apps: the initial state is from the server and then we don't change the context without a full reload.
So we won't handle context changes on the client.
Final design:
The SDK is initialized with a config that includes:
flags: an object of flag definitions (for evaluation on the server and client if needed) OR we might have the server evaluate and send only the values? We need the definitions on the client if we want to re-evaluate? But we don't re-evaluate on the client, we just store the values from the server and from fetches.
So we don't need the definitions on the client? We only need the values. But then if we want to re-evaluate (for example, if we don't have realtime updates and the context changes) we can't.
Let's change: we don't need the definitions on the client. We only need the values. So the server sends the evaluated values and the client stores them.
Then the config on the client doesn't need the flags object? We can have:
config = {
flagsEndpoint: '/api/flags', // to fetch the latest values
analytics: { ... }
}
And on the server, we need the flags definitions to evaluate.
So we have two different configs? Or we can have:
On server: we provide flags (definitions) and optionally flagsEndpoint (for the client to fetch).
On client: we provide flagsEndpoint and analytics.
But then the same config object is used on both? We can have:
const config = {
flags: { ... }, // only on server
flagsEndpoint: '/api/flags', // on both? The server might not need it.
analytics: { ... }
};
Then on the server, we use config.flags to evaluate and ignore flagsEndpoint? And on the client, we don't have config.flags (or it's empty) and we use flagsEndpoint.
We can make flags optional on the client? But then the evaluate method on the client would not work without definitions? We don't call evaluate on the client because we are using the stored values.
So:
On the server, we call evaluate and evaluateAll to get the values and then we send those values to the client.
On the client, we don't call evaluate (except maybe if we want to re-evaluate for a new context? but we don't support that). We just use getFlag and subscribe.
So we don't need the flag definitions on the client.
Then the client SDK only stores the values and provides a way to get them and subscribe.
We can change the client SDK to not have the evaluate method? Or we can leave it but it would require the definitions? We can have:
The client SDK does not have the flags config, so evaluate would throw.
Alternatively, we can have two different classes: ServerFeatureFlagSDK and ClientFeatureFlagSDK.
Let's create:
class BaseFeatureFlagSDK {
// common code: subscribers, analytics, etc.
}
evaluate(flagKey, context) {
// use this.flags[flagKey] to evaluate
}
evaluateAll(context) {
// evaluate all
}
// We don't need rehydrate or realtime updates on server.
}
class ClientFeatureFlagSDK extends BaseFeatureFlagSDK {
constructor(config) {
super(config);
this.flags = new Map(); // store values
}
code
rehydrate(serverState) {
// set the map and track initial values for analytics.
}
getFlag(flagKey) {
return this.flags.get(flagKey);
}
// We don't have evaluate method? Or we can have it but it would require definitions? We don't have definitions.
// So we remove evaluate from the client? Or we can have a method that just returns the stored value? That's getFlag.
// But then the React hook uses `getFlag`, so it's fine.
// We also have the realtime update methods.
}
This way, we separate the concerns.
However, we want the same interface for the React provider? We can have:
The provider uses the ClientFeatureFlagSDK and provides an interface with getFlag and subscribe.
And the server code uses the ServerFeatureFlagSDK and calls evaluateAll to get the state.
This seems cleaner.
Let's refactor:
BaseFeatureFlagSDK:
has analytics, subscribers, and methods for tracking and notifying.
ServerFeatureFlagSDK:
has flag definitions.
evaluate(flagKey, context) -> value
evaluateAll(context) -> { key: value }
ClientFeatureFlagSDK:
has a map of flag values.
rehydrate(serverState): set the map and track initial values (for analytics).
getFlag(flagKey): returns the value.
subscribe(callback, flagKey): subscribe to changes.
startRealtimeUpdates(): fetch and update periodically.
We don't have evaluate because we don't have definitions.
But wait: what if we want to evaluate a flag on the client with a new context? We don't support that.
How about the React hook? It uses getFlag and subscribe.
Analytics:
In the BaseFeatureFlagSDK:
sendAnalytics(event) {
if (this.config.analytics?.enabled && !this.isServer) {
this.config.analytics.send(event);
}
}
But the ClientFeatureFlagSDK is not server, so it will send.
We want to track:
On rehydrate: for each flag, we track the initial value? We can do:
On update from realtime: for each changed flag, we track the new value? We can do in updateState:
for (const key of changedKeys) {
this.sendAnalytics({ type: 'change', flag: key, value: newValue, oldValue, timestamp: Date.now() });
}
But then we are tracking two types: impression and change.
We can have a single type 'evaluation' and then we don't distinguish? But we might want to know if it's an initial impression or a change.
Alternatively, we can track every evaluation (every time the value is set in the store) and then we don't need to distinguish? But then we are tracking the initial set and every change.
That might be acceptable.
We can change:
In rehydrate and updateState, when we set a flag value, we track.
But note: in rehydrate we set all flags, so we track all of them. In updateState we track only the changed ones.
That seems okay.
Conclusion:
We'll have:
BaseFeatureFlagSDK: handles analytics and subscriptions.
ServerFeatureFlagSDK: evaluates flags using definitions.
ClientFeatureFlagSDK: stores values, rehydrates, updates, and provides getFlag and subscribe.
Then we use the appropriate one on server and client.
notifySubscribers(flagKey, newValue, oldValue) {
for (const sub of this.subscribers) {
if (sub.flagKey === null || sub.flagKey === flagKey) {
sub.callback(flagKey, newValue, oldValue);
}
}
}
}
Server SDK:
class ServerFeatureFlagSDK extends BaseFeatureFlagSDK {
constructor(config) {
super(config);
this.flags = config.flags; // object of flag definitions
}
evaluate(flagKey, context = {}) {
const definition = this.flags[flagKey];
if (!definition) {
throw new Error(Flag ${flagKey} not found);
}
const value = this.evaluateDefinition(definition, context);
return value;
}
evaluateDefinition(definition, context) {
if (typeof definition === 'function') {
return definition(context);
}
// If definition is an object, we might have a value property or a more complex rule.
// For now, we just return the value.
return definition.value;
}
evaluateAll(context = {}) {
const result = {};
for (const [key, definition] of Object.entries(this.flags)) {
result[key] = this.evaluate(key, context);
}
return result;
}
}
Client SDK:
class ClientFeatureFlagSDK extends BaseFeatureFlagSDK {
constructor(config) {
super(config);
this.flags = new Map();
this.config = config;
}
rehydrate(serverState) {
// serverState is an object: { flagKey: value, ... }
for (const [key, value] of Object.entries(serverState)) {
this.flags.set(key, value);
this.sendAnalytics({
type: 'rehydrate',
flag: key,
value,
timestamp: Date.now()
});
}
this.notifySubscribers(); // notify all subscribers that the initial state is set.
}
async startRealtimeUpdates(pollInterval = 60000) {
// We'll set up an interval to fetch the latest state.
this.pollInterval = pollInterval;
this.pollTimer = setInterval(() => {
this.fetchLatestState();
}, pollInterval);
// Also fetch immediately?
this.fetchLatestState();
}
stopRealtimeUpdates() {
if (this.pollTimer) {
clearInterval(this.pollTimer);
}
}
async fetchLatestState() {
try {
const response = await fetch(this.config.flagsEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}) // we might send context? But we don't have context on client? We can send user ID if available?
});
if (!response.ok) {
throw new Error(Failed to fetch flags: ${response.statusText});
}
const newState = await response.json();
this.updateState(newState);
} catch (error) {
console.error('Failed to fetch latest flag state:', error);
}
}
updateState(newState) {
// newState is an object: { flagKey: value, ... }
const oldState = Object.fromEntries(this.flags);
const changedKeys = [];
code
for (const [key, value] of Object.entries(newState)) {
const oldValue = this.flags.get(key);
if (oldValue !== value) {
this.flags.set(key, value);
changedKeys.push(key);
this.sendAnalytics({
type: 'update',
flag: key,
value,
oldValue,
timestamp: Date.now()
});
}
}
// Notify subscribers for changed flags.
for (const key of changedKeys) {
this.notifySubscribers(key, this.flags.get(key), oldState[key]);
}
}
}
React provider:
We'll create a context and a provider that creates the client SDK and rehydrates.
We assume the server passes the serverState as a prop to the provider.
We also need to clean up the realtime updates when the component unmounts.
We'll use useMemo to create the SDK instance and useEffect to start realtime updates.
We'll also provide a way to manually refresh? Maybe not in the provider.
export function useFlag(flagKey) {
const sdk = React.useContext(FlagContext);
if (!sdk) {
throw new Error('useFlag must be used within a FlagProvider');
}
Then we pass flagState to the client as a prop to the FlagProvider.
Analytics beacon:
The config.analytics.send function should be implemented by the user. For example:
const analytics = {
enabled: true,
send: (event) => {
// Use sendBeacon if available, or fallback to fetch
if (navigator.sendBeacon) {
const blob = new Blob([JSON.stringify(event)], { type: 'application/json' });
navigator.sendBeacon('/analytics', blob);
} else {
fetch('/analytics', {
method: 'POST',
body: JSON.stringify(event),
keepalive: true
});
}
}
};
And then pass this in the config.
Limitations:
We assume the flag definitions are static on the client? We don't update them. If the flag definitions change, the client will still use the old ones until we update the config? But we don't have a way to update the config.
We don't support context changes on the client without a full reload.
The realtime updates fetch the entire state and replace the local state. We don't merge with the existing state? We do replace, but we only track changes for the keys that are in the fetched state. We don't remove keys that are not in the fetched state? Actually, we replace the entire map, so we remove keys that are not in the fetched state.
But what if the server sent a flag that is not in the fetched state? We remove it? That might be intended? Or we might want to keep the server state for flags that are not in the fetched state?
// Update existing and add new.
for (const [key, value] of Object.entries(newState)) {
const oldValue = this.flags.get(key);
if (oldValue !== value) {
this.flags.set(key, value);
changedKeys.push(key);
this.sendAnalytics({ ... });
}
}
// What about keys that are in oldState but not in newState? We remove them? Or we keep?
// We can remove them? Then we are effectively replacing the state.
// But then if a flag is removed on the server, we remove it on the client.
// We can do:
for (const key of oldState.keys()) {
if (!(key in newState)) {
this.flags.delete(key);
changedKeys.push(key);
this.sendAnalytics({ flag: key, value: undefined, oldValue: oldState[key] });
}
}
// Then notify for changedKeys.
}
But then we are tracking removals? We might not want to track removals? We can track as value: null.
Alternatively, we can just replace the entire map and then notify for all keys that changed? We can compare the entire map and notify for every key that has a different value.
We can do:
const newMap = new Map(Object.entries(newState));
const changedKeys = [];
for (const [key, oldValue] of this.flags) {
const newValue = newMap.get(key);
if (oldValue !== newValue) {
changedKeys.push(key);
this.sendAnalytics({ ... });
}
}
// Also for keys that are in newMap but not in this.flags, we consider them as changed (from undefined to value).
for (const [key, newValue] of newMap) {
if (!this.flags.has(key)) {
changedKeys.push(key);
this.sendAnalytics({ ... });
}
}
this.flags = newMap;
Then notify for all changedKeys.
This way we handle added, updated, and removed flags.
However, note: the server state initially might have flags that are not in the fetched state? We don't want to remove them until we get a fetched state that doesn't have them? But the fetched state is the source of truth for the client? We are replacing the entire state with the fetched state, so we remove any flags that are not in the fetched state.
But what if the server sent a flag that is not in the fetched state because the fetched state is only a subset? Then we remove it? That might be wrong.
We need to decide: is the fetched state the complete state? We assumed it is. If it's not, then we should merge? But then we don't know which flags are dynamic and which are static.
Given the complexity, we will assume the fetched state is the complete state. So we replace the entire map.
Then we don't need to worry about removals because the fetched state doesn't have the flag, so we remove it.
So we can do:
updateState(newState) {
const oldState = Object.fromEntries(this.flags);
this.flags = new Map(Object.entries(newState));
code
// Notify for every key that changed (including removals and additions)
const allKeys = new Set([...Object.keys(oldState), ...Object.keys(newState)]);
for (const key of allKeys) {
const oldValue = oldState[key];
const newValue = newState[key];
if (oldValue !== newValue) {
this.sendAnalytics({
type: 'update',
flag: key,
value: newValue,
oldValue,
timestamp: Date.now()
});
this.notifySubscribers(key, newValue, oldValue);
}
}
}
This way we catch additions, updates, and removals.
Final note:
This is a complex SDK and we have made many assumptions. We might need to adjust based on actual requirements.
But given the problem statement, this should be a good starting point.