Connection Pooling with Azure COSMOS Python Client

Tanuj Mittal 20 Reputation points
2024-10-28T15:49:40.4466667+00:00

I am using the below code to retrieve items from Azure COSMOS DB. This code is part of a WebAPI and the code will run in multiple threads. Which of the following objects are thread-safe:

db_client, database, container ?

Can I create a singleton for container (assuming all my threads read item from the same container) ?

db_client = cosmos_client.CosmosClient(url, {'masterKey': key})
database = db_client.get_database_client(config["database_name"])
container = database.get_container_client(config["container_name"])
existing_item = container.read_item(item="item_key", partition_key="item_key")
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,681 questions
{count} votes

Accepted answer
  1. Azar 22,955 Reputation points MVP
    2024-10-28T16:14:34.39+00:00

    Thats a great question Tanuj Mittal

    and thanks for usijng QandA platform

    i beleoive Yes, the CosmosClient instance is thread-safe. and its good to use a single instance foir the lifetime.

    The DatabaseProxy object is also thread-safe as it is derived from the CosmosClient.

    So, you can definitely create a singleton for the container if all your threads are reading from the same container.

    If this helps kindly accpt the response thanks much.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.