Hi, the Node.js SDK <docs> mention to: &gt; Create...
# announcements
l
Hi, the Node.js SDK docs mention to:
Create a separate GrowthBook instance for every incoming request. This is easiest if you use a middleware:
May I know why a separate instance needs to be instantiated for each request? Wouldn't this create many instances proportional to the traffic the server is handling? Is it possible to have a cached GrowthBook instance across the server and we just add it to the
req
property and override the attributes if required like
req.growthbook.setAttributes({...})
for incoming requests?
h
Your intuition is correct in wanting a cached version of features/experiments across all requests, and in fact that's exactly how our SDK works behind the scenes. Our JS and React SDKs create a shared, cached singleton across all SDK instances and each new SDK instance is just a thin, short-lived wrapper around that singleton. This allows each SDK instance to be user-specific (based on attributes) while still tapping into the central feature repository.
l
Ah I see. Got it, thanks for explaining @happy-autumn-40938!
😁 1
@happy-autumn-40938 I have a follow up question for backend usage: The recommended approach creates and introduces a
growthbook
property within the Express
req
object at a middleware level Let's say you have a downstream service (e.g. serviceC) depending on a feature flag. E.g. middleware -> controller -> serviceA -> serviceB -> serviceC Does this mean that I need the pass the
growthbook
object from req from the controller level all the way down to serviceC? This seems similar to "prop-drilling" Is there a way serviceC can just obtain the singleton from the SDK? I considered just initialising a new SDK instance in serviceC and reading the value of the flag. This would work for normal usage but not for percentage-based rollouts which would depend on the attributes set by the middleware layer (e.g. an authorization middleware that sets user-specific attributes like email and role). Is there any recommended approach here?
h
The issue here is that your singleton does not have anything user-specific in it. So if you're simply using feature flags as global on/off switches for everybody, then instantiating a new SDK instance within serviceC (and reading from the singleton) works fine. But ultimately you'll probably want user-based targeting, especially for experimentation. There's no good way to avoid prop drilling in this case, although you can "smooth it over" a bit by putting either the evaluated feature results or even just the user's SDK instance into a shared
ctx
object and passing that between services.
l
I guess I will inject the user's SDK instance into a
ctx
as you suggested. Thanks for the input @happy-autumn-40938!