Skip to content

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

@aldipower

Description

@aldipower

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions