node-gettext icon indicating copy to clipboard operation
node-gettext copied to clipboard

Recipe to prevent race conditions with setLocale on server-side?

Open aldipower opened this issue 1 year ago • 5 comments

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:

const Gettext = require('node-gettext');

// This is a "singleton" context
const gettext = new Gettext();

gettext.addTranslations('de', 'messages', JSON.parse(translationFile));

// This creates a new sub-context on each request
app.get('/:lang', function (req, res) {
    const locale = req.params.lang;

    // This set the locale in the upper context which is shared by each request!
    gettext.setLocale(locale);

    // Do some heavy work here ....

    // Again we are accessing the upper gettext-context
    res.send(gettext.gettext('Translation probably with the wrong locale!'));
});

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:

gettext.setLocale(locale, "my-context-id");

res.send(gettext.gettext("my-context-id")('Translation probably with the wrong locale!'));

What do you think?

aldipower avatar Oct 20 '22 09:10 aldipower