Race Condition when localizing text in typescript
What project is affected?
botbuilder-solutions
What language is this in?
typescript / javascript
What happens?
When sending multiple localized responses to a user separated by a long-running process, a race condition can be triggered by having another user using another locale interact with the bot. The locale for the first user is set to the locale of the second user and then the subsequent responses for the first user are sent in the 2nd user's locale
What are the steps to reproduce this issue?
User 1: Sends utterance to bot Bot: Checks the activity locale and sets the i18next.language global variable to User 1's locale Bot: Sends Message 1 to User 1 in User 1's locale Bot: Engages in a long-running process (a REST call for example) and awaits its completion User 2: Sends utterance to bot Bot: Checks the activity locale and sets the i18next.language global variable to User 2's locale Bot: Sends Message 1 to User 2 in User 2's locale Bot: Finishes long running call by User 1 and resumes working on his request Bot: Sends Message 2 to User 1 in User 2's locale
Checking the activity locale and setting the i18next.language variable happens in the SetLocaleMiddleware. Both the old ResponseManager and the LocaleTemplateEngineManager use the i18next.language global variable to determine which localized version of a response to send, so the issue occurs also in the new 0.7 release.
What were you expecting to happen?
User activities should be localized according to his own locale and not be affected by the locale of other users.
Can you share any logs, error output, etc.?
This is a minimum running example that you can place in any VA or skill's mainDialog to reproduce the issue:
protected async route(dc: DialogContext): Promise<void> {
await dc.context.sendActivity(this.responseManager.getResponse(MainResponses.completed));
await this.longRunningOperation();
await dc.context.sendActivity(this.responseManager.getResponse(MainResponses.completed));
return;
}
protected async longRunningOperation(): Promise<void> {
return new Promise(resolve => setTimeout(resolve, 5000));
}
Any screenshots or additional context?
The first message exchange depicts the normal scenario, while the second exchange depicts the scenario I describe above and can be reproduced using the code I provided. If a user with a german locale sends a message to the bot while it's awaiting User 1's long running operation, the next message sent to User 1 will be in the german locale

Thanks @marawanshalaby, we will investigate this.
In our next release we are taking on a dependency of the LanguageGeneration library for a LocaleTemplateEngineManager and need to check what it does for the global variable.
hey @ryanlengel, thanks for the reply. While I am still currently using the 0.6 version, I have checked out how the LocaleTemplateEngineManager does the localization, and it too depends on the i18next.language global variable, so it should also have the same problem
Maybe to add a bit of context to this issue, when express uses i18next to do localization, it first clones the global instance and then attaches that instance to the user's request so that it's no longer a global variable. It then uses this request-local instance to do the actual translation
Thanks @marawanshalaby! We will be checking this issue and we will back to you later 😊.
sorry for the constant messages, but we just encountered the same problem (race condition when code sets a global variable to respond to different user requests) in an unrelated component 2 days ago and we came up with a solution to use Continuation-Local Storage to easily keep context related to a single user's request in a single and globally accessible place (same idea as Thread-Local storage for C#/Java, but for the single-threaded callback-based nodejs world). We used this library https://github.com/jeff-lewis/cls-hooked for that and our code goes something like this:
# during the initialization of our skill (`index.ts`)
const cls = require('cls-hooked');
const namespaceId = "myAppNamespace";
const ns = cls.createNamespace(namespaceId);
# when receiving a user request (in the handler for `server.post('/api/messages', {})`
ns.set('requestLocalProperty', propertyValue);
#... later on when you need to get some info in this continuation-local storage
ns.get('requestLocalProperty')
The namespace basically acts as a global registry and we hide all of this logic behind a singleton (not shown here for simplicity). I see it possible to do something similar for the LocaleTemplateEngineManager where a cloned version of the i18next object can be attached to the continuation-local storage when receiving the user request (this part can be taken care of internally by the adapter instead of adding code to the skill itself), and then that instance can be retrieved by the LocaleTemplateEngineManager when localizing responses, instead of using the global i18next.language instance.
This is only a suggestion, I am sure there are better ways to fix this issue.
Hi @marawanshalaby! We successfully reproduced this issue in TypeScript version. Currently, we are implementing and testing different scenarios to fix the race condition problem, we will back to you later with the latest updates about this 😊.
Using two different locales to reproduced the issue.

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days
HI, @DiegoCardozo94, @Batta32 this is still open right?
Hi @tommyjimmy87! We are still reviewing this issue related to Race Condition in TypeScript.
Currently, we continue working on the alternative to fix the Race Condition scenario in the bots, containing these changes:
- Remove i18next library from TypeScript solutions
- Store the request's locale in the activity
We will validate the end-to-end behavior of these changes in the Virtual Assistant Sample and the Skill making the necessary changes in both bots for TypeScript version.
Race Condition is fixed applying the alternative explained above

Additional Context We validated different solutions to fix the Race Condition situation. However, none of these options worked out as we expected:
- We set the proper language to the global i18next instance and cloned this global instance, as the user recommended us, placing it on the activity's value property for each request.
- We implemented the library cls-hooked to emulate the thread safe as C# version changing the i18next global variables into locals and this library works with Namespaces.
We will back later with the latest updates about this 😊.
@DiegoCardozo94 thanks, yes we use the cls-hooked library for Logging purpose with Typescript and looks like it's working well. The thing here is that you have to re-initialize the language variable every time you receive a request per user.
Hi @marawanshalaby, we created the PR #3411 which solves the problem of race condition.
If you are so kind, can you validate the changes following these repro steps and using this branch:
- Go to bot-solutions library
- Execute
npm installto install the dependencies - Execute
npm run buildto compile the solution - Execute
npm packto create thetgz - Go to the Virtual Assistant Sample
- Use the created
tgzin the Virtual Assistant package.json as follows:
"bot-solutions": "PATH TO BOT-SOLUTIONS TGZ"
- Deploy the Virtual Assistant in multi languages
- Follow the steps to reproduce the race condition scenario you mentioned
Last but not least, as it was mentioned, the PR contains the following changes:
- Store the locale in the activity
- Remove of
i18next
We will be attentive to your answer 😊.
Thanks @Batta32 We’ll try this out asap!
Hi @Batta32, I tried the scenario we mentioned at the beginning of this issue and it's working good ( I didn't try it from the sample, but instead, I integrated the changes in our project)
Though, we have some problem with the QnA Maker dialog, we have multiple QnA knowledge base (not just faq and chitchat) :
Here the usecase:
User 1: Sends utterance to the bot ( DE );
Bot: The Bot resolves the utterance as QnA intent, and create the new QnADialog, with the knowledgebaseId as Id of the Dialog:
private registerQnADialog(knowledgebaseId: string, cognitiveModels: ICognitiveModelSet, locale: string): void {
const qnaEndpoint: QnAMakerEndpoint | undefined = cognitiveModels.qnaConfiguration.get(knowledgebaseId);
if (qnaEndpoint == undefined){
throw new Error(`Could not find QnA Maker knowledge base configuration with id: ${ knowledgebaseId }.`);
}
if (this.dialogs.find(knowledgebaseId) == undefined) {
const qnaDialog: QnAMakerDialog = new QnAMakerDialog(
qnaEndpoint.knowledgeBaseId,
qnaEndpoint.endpointKey,
// The following line is a workaround until the method getQnAClient of QnAMakerDialog is fixed
// as per issue https://github.com/microsoft/botbuilder-js/issues/1885
new URL(qnaEndpoint.host).hostname.split('.')[0],
this.templateEngine.generateActivityForLocale('UnsupportedMessage', locale) as Activity,
// Before, instead of 'undefined' a '0.3' value was used in the following line
undefined,
this.templateEngine.generateActivityForLocale('QnaMakerAdaptiveLearningCardTitle', locale).text,
this.templateEngine.generateActivityForLocale('QnaMakerNoMatchText', locale).text
);
qnaDialog.id = knowledgebaseId;
this.addDialog(qnaDialog);
}
}
Bot: Sends QnA Answer to User 1 in User 1's locale ( DE )
User 2: Sends utterance to bot ( EN );
Bot: The Bot resolves the utterance as QnA intent ( same the user 1 sent ), no new QnaMakerDialog is created because one Dialog with the same knowledgebaseId already exists.
Bot: The Bot start again the QnA Dialog (added from user 1 iteration) and get the answer from the Knowledge Base (DE) of the first user;
Bot: Sends Message to User 2 in User 1's locale.
So, now just to add a bit more of context, we have the same knowledge base ID ( "id": "chitchat" for example which is the knowledgeBases[0].id not kbId in the cognitivemodels.json ) for different languages, is this changed with the new version? Otherwise, I guess the Dialog is added just once with the first language it receives.
Or maybe I have some misconfiguration which is also possible :/
Thanks @tommyJimmy87 for validating the PR #3411, we will be double-checking the changes so we can put it ready for review.
We already noticed the issue you mentioned and we are currently working to fix it.
As soon as we have any update we will be back to this thread 😊.
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days
@marawanshalaby & @tommyJimmy87 , this issue was solved in PR #3411 and it will be present in the next release.
I will close this issue, feel free to re open it.
Hi @Batta32, thanks! It is also the QnaMakerDialog problem solved? The one I described above in the previous comment and test.
Thanks @tommyJimmy87 , we are currently working on that issue implementing Dependency Injection.
Can you create the QnAMakerDialog issue in the repository so we can follow up?