2

I was tinkering with repository pattern for CosmosDB. I have modified the code to have a singleton CosmosDb DocumentClient. Every instance of the repository is making network calls to fetch Database & DocumentCollection. So I want to know whether it is right to cache the Database & DoumentCollection objects, as in my case I will only have one collection & one database.

Vivek Sasidharan
  • 1,265
  • 3
  • 17
  • 34

1 Answers1

2

A lot of "demo" code you see is "incorrect" as it is a few lines of code to create or read something from CosmosDB. This will work fine without a singleton due to low volumes. Scale a simple operation up to a high volume multi threaded application and you will see problems.

In order to avoid issues, you should only create one DocumentClient per CosmosDB instance and one DocumentCollection per collection in your database otherwise you will incur the additional overhead of unnecessary instantiation and under high load you will experience socket exhaustion.

We mark ours as volatile (C#) too:

private static volatile DocumentClient cosmosClient;
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86
  • 1
    Will the ETag create any issues? – Vivek Sasidharan Mar 06 '18 at 12:11
  • The ETag is part of the FeedResponse, it is not held on the Client or Collection. – Murray Foxcroft Mar 06 '18 at 12:14
  • But the ETag is a property of `DocumentCollection` class, right? And what about Caching the `Database` object as well? – Vivek Sasidharan Mar 06 '18 at 12:18
  • Each document has it's own ETag. The ETag on the collection is only for changes to the actual collection. If you are modifying the collection's properties regularly (unlikely) then you may want to periodically refresh your collection object or create some strategy to deal with it (e.g. restart your app if you modify the collection's properties). – Murray Foxcroft Mar 06 '18 at 12:22
  • Ok. Understood. So what about the `Document` object? Can I cache that too? – Vivek Sasidharan Mar 06 '18 at 12:23
  • 1
    We cache the database too (in a Dictionary). You can cache a document if you need to but remember that cached objects can become stale and you need to manage that. When writing the document back you can check the ETag to see if it has been modified by some other system / code. – Murray Foxcroft Mar 06 '18 at 12:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166314/discussion-between-vivek-and-murray-foxcroft). – Vivek Sasidharan Mar 06 '18 at 12:46