View indexing blocking main thread with Couchbase Lite

I have an iOS application that stores mass amounts of data. I run my view queries on a worker thread, however, the first time I run the query the application locks up for several seconds for what I presume is indexing. Every subsequent call does not block the main thread. Does any one know how to void this initial thread blocking? I will provide more detail if needed.

Are you using separate objects per thread to access the db? See Concurrency Support here.

I am using the backgroundTellDatabaseNamed(:_) function to perform the query and when its finished it returns, in a callback, initialized struct objects that represent the documents in the database. However, I have a class, DatabaseService, that is a singleton holding the opened database. I make frequent calls to the database, so I prefer to keep it open during the user’s session, and some calls are synchronous with the main thread, e.g. getting a single item from the db, and some asynchronous, e.g. querying a view holding >1k documents.

The only issue I am having is when I first query a view, it locks the main thread for a few seconds for what I presume is indexing, because after one query has been done on a view, each query after that runs asynchronously as I expected.

I don’t think it’s that it is running asynchronously it just needs to run the initial indexing before it can query. The index is persisted so that next time you run a query it doesn’t need to index much if anything.

Keeping the db open is fine. You need separate manager instances and such per thread though. See, e.g., this issue discussion on github.

Hod

SQLite allows only one database connection to write to the database at a time. Couchbase Lite has been a bit stricter than that, only allowing one connection to access the database; this means that when one thread is writing, other threads are blocked when they try to read. This is what you’re seeing.

Shortly after 1.3.1 I made a change to our transaction logic that allows readers simultaneously with a writer. This should improve concurrency a lot. This will be in the 1.4 release; if you don’t want to wait, you can download a recent build here or check out and build your own.

(Even with this build you’ll still block the main thread if you try to write from it. But reads will not block.)