-
Notifications
You must be signed in to change notification settings - Fork 36
-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Recipe to prevent race conditions with setLocale on server-side? #67
Comments
I've found a workaround for the race condition. Performance wise it does not feel ideal, but at least it works. :) If you initialize Gettext in each request, you won't have races. const Gettext = require('node-gettext');
app.get('/:lang', function (req, res) {
const gettext = new Gettext();
gettext.addTranslations('de', 'messages', JSON.parse(translationFile));
const locale = req.params.lang;
gettext.setLocale(locale);
// Do some heavy work here ....
res.send(gettext.gettext('Translation probably with the wrong locale!'));
}); |
The problem with that is |
@aldipower What about the following workaround?
|
You have to create a singleton instance per request. This library doesn't offer you any other solution |
You could also create a map of gettext instances based on locale, and then retrieve the correct one in the request. const de = new Gettext()
de.addTranslations('de', 'messages', deTranslations)
de.setLocale('de')
// etc for other locales
const gettexts = {
de: de,
en_EN: en_EN,
}
app.get('/:lang', function(req, res) {
const gettext = gettexts[req.params.lang]
}) |
Hi! I a found a potential problem, which could occur on high traffic sites with the concept of
setLocale
.Does anybody worked around this already?
I give you a code example straight away - imagine hundreds of simultaneous requests per second:
If you read the code, you will see, this leads to race conditions on heavy requested sites!
On low traffic sites you probably won't notice. But if your site gets more popular, s*it hits the fan.
How could we prevent this?
We could contextualize the
setLocale
itself?For example:
What do you think?
The text was updated successfully, but these errors were encountered: