Checking if a bucket is initialised & ready


#1

Hi there,

I am trying to create a bucket if one doesn’t already exist and create a primary index on it. I’ve found that if I create the bucket and immediately try to run a N1QL query (or anything in fact) on it, it will fail. If I wait a few seconds, it seems to work most of the time. When it fails I get an AggregateException which contains an InnerException with just the bucket name and nothing else "{ "bar-data" }".

Is there a way to check that bucket is initialised and ready? Or a way to wait for the create procedure to finish? I’ve had to add a wait in as a (terrible) workaround. See my simplified code below:

ClusterHelper.Initialize("couchbaseClients/couchbase");

var clusterManager = ClusterHelper.Get().CreateManager("user", "pass");
var bucketList = clusterManager.ListBuckets().Value;
if (bucketList == null)    
    throw new Exception();

var bucketConfig = bucketList.FirstOrDefault(p => p.Name == "bar-data");

if (bucketConfig == null)
{
    clusterManager.CreateBucket("bar-data");

    System.Threading.Thread.Sleep(5000); // <-- I want to avoid this.

    ClusterHelper
        .GetBucket("bar-data")
        .Query<dynamic>("CREATE PRIMARY INDEX `bar-data-index` ON `bar-data`;");
}

Also is there an easier way of checking if a bucket exists?


#2

@molexmat -

Unfortunately creating a bucket requires the allocation of system resources on the server and takes time. Probably the best way to determine when the bucket is fully initialized would be to poll the server until it becomes initialized and then continue from there. You could do this on a separate thread and use a callback to alert the app that the bucket is ready. I would probably use an exponential back-off algorithm here.

That being said, in general it’s not a best practice to create buckets on the fly if you do not have to. I know for some use cases it’s required, for example provisioning in a cloud scenario.

-Jeff