Showing posts with label couchbase. Show all posts
Showing posts with label couchbase. Show all posts

Saturday, July 20, 2019

Good practices for Accessing Couchbase Programatically

Couchbase is one of the most popular distributed, fault-tolerant, and highly performant Document-oriented as well as a key-value store. Like any other database (relational or NoSQL), Couchbase provides language-specific Client SDK to access DB and perform CRUD operations.  You can also access Couchbase through the command-line tool, cbc or from the Couchbase web console. 

This post will focus on some of the good practices for accessing Couchbase.  I will be using Java SDK for this post; the concepts are applicable for any language though.

Initialize the Connection

All operations performed against Couchbase (cluster) is through Bucket instance.  From the relational world perspective, Bucket is the database instance.  And to create bucket instance, we need to have the instance of the Cluster. 

The important point to be noted is that we should only create ONE connection to the Couchbase cluster and ONE connection to each bucket, and then statically reference those connections for use across the application. Reusing the connections will ensure that underlying resources are utilized to the fullest. 

// connects to cluster running on localhost
Cluster cluster = CouchbaseCluster.create();   
// Connects cluster on 10.0.0.1 and if it fails then tries 10.0.0.2
Custer cluster = CouchbaseCluster.create("10.0.0.1", "10.0.0.2");

Now, the Cluster instance is created, we can create Bucket instance to complete the initialization.

// Opens the default bucket
Bucket bucket = cluster.openBucket();   
// Opens connections to demo bucket
Bucket bucket = cluster.openBucket("demo");   
// Opens connections to SECURED demo bucket
Bucket bucket = cluster.openBucket("demo", "p@ssword");   

Tips#
It's good practice to pass at least two IP addresses in the create method.  At the time of this call if the first host is down (for some reason); 2nd host will be tried. These IPs will be used only during initialization. If there is only one host and it's down, then you are out of luck and bucket instance will not be created!

Saturday, October 7, 2017

Identifying Right Node in Couchbase

This post covers - how Couchbase achieves data partitioning and Replication. 

doc = "{"key1":"value1".....}"  ; doc-id = id

Steps:

  • Based on key (or document id) the hash gets calculated.
  • Hash returns a value in the range [0,1023] both inclusive. This is known as partition id.
    • number basically maps the document to one of the vBuckets. 
  • Next task is to map the vBucket to a physical node. This gets decided by vBucket Map.
    • This maps tells which is the primary node for the document and which all are the backup nodes.   vBucket Map will have 1024 entries, one of each vBucket. And each entry also an array. The first value is for primary node and rest all are replica nodes.
  • Server list stores list of live nodes. So based on the index of the vBucketMap, we get to know the physical node IP address.



Tuesday, August 15, 2017

Couchbase Primary vs Secondary Indexes

Couchbase supports key-value as well as JSON based data model. In Key-value model you don't care about the type of value. In JSON model you have ability to perform queries on the individual attributes using N1QL queries.


Key-Value Model 

Without Index
Key-value store is schema less where the object gets mapped to a given key (Just like a HashMap or Dictionary).   Couchbase is more like a distributed HashMap. The value could be any supported data type (JSON, CSV, or BLOB). You perform any operation using the key or Document Id. In this case, Couchbase looks up the value corresponding to a given document id. In simple terms, it's just like a key lookup in a HashMap. Index doesn't play any role here.


Query: bucket.get(docId);


With Index
Now what if you want number of documents in your bucket ?

Query: SELECT COUNT(*) FROM `bucket-name`

Above query is going to do full Bucket scan (similar to full table scan in SQL world). In SQL world, index on primary key gets created by default so you can easily perform above operation. But, in Couchbase, that's not the case. You will have to create explicit index to perform above query or any other ad-hoc query. So, if you want to create an index on the the key or document id, we can create primary index. 

Query: Create PRIMARY INDEX index_name on `bucket-name`


JSON Model (Secondary Indexes)

If you want to complete control on your data and queries, Json model is going to be your choice. In above approaches you can't say like give me all the objects which has certain attribute value. 

In JSON based model, we can query through a SQL like expressive language named as N1QL(pronounced as nickel). This is much more flexible model, we can look for a document(s) through the keys contained inside JSON. Obviously, to optimise lookup/search we can create index on those attributes. These indexes are named as secondary indexes or more precisely Global Seconday Indexes.

Query: CREATE INDEX type_index ON `bucket-name`(type) USING GSI



Primary vs Secondary Indexes


  • Primary indexes index all the keys in a given bucket and are used when a secondary index cannot be used to satisfy a query and a full bucket scan is required. 
  • Secondary indexes can index a subset of the items in a given bucket and are used to make queries targeting a specific subset of fields more efficiently. 


--- happy learning !

Friday, August 11, 2017

RAM sizing Data Node of Couchbase Cluster

This post talks about finding out how much RAM does your Couchbase cluster needs for holding your Data (in RAM)! 


RAM Calculator 

RAM is one of the most crucial areas to size correctly. Cached documents allow the reads to be served at low latency and high throughput.  Please note that, this doesn't not incorporate RAM requirement from the host/VM OS and other applications running along with Couchbase.

Enter below fields to estimate RAM -

Sample Document        (key)    (Value) 
This is required as document content length as well as ID length impacts RAM. Be mindful of the size aspect when deciding your key generation strategy. 


# Replicas                                        
Couchbase only supports upto 3 replicas. So enter either - 1, 2 or 3.


% Of Data you want to be in RAM  %
For best throughput you need to have all your documents in RAM i.e. 100% . This way any request will be served from RAM and there will be no IO.  In the field please enter only the value like 80, 100 etc. 


# Documents                                   
Number of documents in the cluster. When your application is starting from scratch then you can start with a number depending on the load of the application and then you need to evaluate it regularly and adjust your RAM quota if required. So, you can start with say 10000 or 1000000 documents. 


Type of Storage                                SSD        HDD
If storage is SSD then overhead % is 25 else it's 30%. SSD will bring better performance in disk throughput and latency. SSD storage will help improved performance if all data is not in the RAM. 


Couchbase Version                        < 2.1       2.1 or higher  
Size of meta data for 2.1 and higher versions is 56 bytes but for lower versions it's 64. 


High Water Mark                             %
If you want to use default value enter 85. 
If the amount of RAM used by documents reaches high water mark (upper threshold), both primary and replica documents are ejected until the memory usage reaches low Water Mark (lower threshold). 

                                                          

Based on the RAM requirement for the cluster, you can plan how many nodes are required. Another important aspect in deciding number of data nodes is how you expect your system to behave if 1, 2 or more nodes go down at the same time. This link, I have discussed about Replication factor and how it affects your system performance. So, take your call wisely!

The value got calculated as explained in the Couchbase link, here.
Reference for calculating document size is, here. 

--- happy sizing :)

Wednesday, August 9, 2017

Replication Factor in Couchbase

One of the core requirement for Distributed DBs is to be as High Availability as possible. What this literally means is that, even if node/nodes go down the DB should function (on its own or with minimum intervention). This is possible only if there are backup copies of the data. 

Replication factor controls number of replicas or backup of an item/data/document stored in a DB. The general rule is to have replica for each node which can fail in the cluster.

Let's check how one of the famous NoSQL distributed Db handles Replication Factor. 

Couchbase


Default replication factor is 1 in Couchbase (if it's enabled). Drop down field (as shown below) has only 3 values i.e. 1, 2 and 3. Practically, it doesn't make sense to have replication factor more than 3 no matter how large your cluster is.

 So even if you have only one node and enable replicas then in the same node there will be two copies of the same data (one original and one backup). Once you add more nodes to the cluster original and replicas will get re-distributed automatically. 


Recommendation:

Number of Nodes <= 5 - RF = 1
5 <= Number Of Nodes <= 10 - RF =2
Number of Nodes > 10 - RF = 3

Number of nodes mentioned above is only for data nodes if you are using Multi Dimensional Scaling.  If you are not using MDS then also above rule should hold good. 

In the event of failure we can fail over (manually or automatically) to replicas. 
  • In a 5 node cluster with 1 replica. If one node goes down cluster can fail it over. Now before the the failed node is up, what if another node goes down ? You are out of luck. You will have to add another node to the cluster. 
  • After a node goes down and it's failed over try to replace that node ASAP and perform rebalance. Rebalance creates the replica copies if there are enough nodes available. 


References

Saturday, April 15, 2017

Understanding Meta data stored by Couchbase for each Document

Along with document, Couchbase also stores some of the important META data. This post talks about those meta details and then also shows how they can be read using N1QL query.

CAS:
CAS is acronym for check-and-set (and compare and swap) and it's a technique to do optimistic locking. This is a unique identifier associated with document which can be used to prevent the update to a document if the CAS value is not same as the original one. The intent is that, instead of (pessimistically) locking the record you read the CAS value along with document and then perform the write if and only if CAS value matches. More details on Couchbase developer pages (recent page, and a bit old link). 

CAS represents the current state of the document and each time the document is modified CAS also gets updated. Couchbase server automatically provides this value for each document and it's type is 64-bit integer. 
More details on CAS here. 

FLAGS:
Identifies type of data stored or formatting. 

ID:
Unique document identifier per bucket. Document ID should conform to UTF-8 encoding. Couchbase stores all keys in RAM, so keep in mind this fact before deciding the length of keys. Also, Couchbase doesn't by default generate keys for the document if you don't provide one explicitly. 


Let's see these details through queries:

N1QL Query


cbq> SELECT meta(b) FROM `bucket_name` b WHERE meta(b).id = "01674B3Z6C3H";
{
    "requestID": "c42ddb7e-75ef-461a-a9df-1b458e4b03fa",
    "signature": {
        "$1": "object"
    },
    "results": [
        {
            "$1": {
                "cas": 1491370937556664300,
                "flags": 33554432,
                "id": "01674B3Z6C3H",
                "type": "json"
            }
        }
    ],
    "status": "success",
    "metrics": {
        "elapsedTime": "100.949282ms",
        "executionTime": "100.869461ms",
        "resultCount": 1,
        "resultSize": 193
    }

}


--happy learning !




Sunday, April 9, 2017

What if one of Couchbase Data Node goes Down

This post talks about impact on your system when one of data nodes of Couchbase is removed from cluster for some reason (software, hardware, or network). In terms of CAP theorem, this actually means that Network Partitioning has occurred. 
Couchbase Version: 4+ (Supports MultiDimensional Scaling). 


Let's make one thing very clear, before digging deeper into this situation. Overall, your system is still functional as only one node is out of cluster (hopefully you have more data nodes :D, and they are live and running!). Only, data which is stored on the down/unreachable node is going to get impacted. 

Couchbase shards data in vBuckets and they get distributed across all the data nodes. So, each data node will have a list of vBucket, some of them will be hosting primary data and others replica data. Nothing happens to replica data, as they will get serviced from their primary node.

Now, real question is how Couchbase is going to deal with the request (read/update/delete) for primary data-

To preserve strong consistency, Couchbase allows access only from primary node. If this is not enforced, and assume (primary) node writes data and immediately goes down (before replication is successful). Now, what if Couchbase decides to service the request from replica node ? Stale data will be returned or updated. This will make system highly Available, but inconsistent.

Couchbase designers chose consistency over availability. So any request for primary data will fail until the node is failed over, which will activate replica data on some other node. To fail over we need to click Fail Over on down node from Couchbase UI. After this we can manually rebalance, in which case data which was not replicated will get lost.

Related Posts:
My MDS in Couchbase
How Couchbase Identifies Node For Data Access
Create Couchbase Cluster using Docker


References
https://forums.couchbase.com/t/what-happens-when-a-node-in-the-cluster-goes-down/36
https://blog.jtclark.ca/2014/07/simple-recovery-of-a-couchbase-cluster-when-one-or-all-nodes-fail/

Saturday, March 11, 2017

Create Couchbase Cluster using Docker

This post walks you through steps to setup Couchbase cluster using Docker. Post expects that you already have Docker installed in your machine (Either of Linux, Mac or Windows)

Before starting the real work, make sure that Docker daemon is up and running.
$ sudo docker info
If daemon is NOT up; you will have something like below on your console:
Cannot connect to the Docker daemon. Is the docker daemon running on this host ?

If daemon is up, then you will have the details like Containers, OS, CPU, OS Name, docker root directory etc printed on the console.

To start Docker daemon (ref)
$ sudo service docker start

Run Couchbase as Dockerized Container

$ sudo docker run -d --name cb1 couchbase
On some of the platforms (like Mac) you need to specify the port mapping as well.
$ sudo docker run -d --name cb1 -p 8091-8094:8091-8094 -p 11210:11210 couchbase:enterprise-4.6.3

Above command runs Couchbase in detached mode (-d) and name is cb1.
$ sudo docker inspect cb1
Above command list all metadata of the cluster in JSON format. One of the important details to look for is IP address (with key IPAddress) of the couchbase server.

To launch couchbase in your browser use URL: http://<<ip_address>>:8091

Lanuch URL and then customize/configure couchbase server. To make it usable, you need to provide details like bucket, RAM, services which you want to run (if it supports multi dimensional scaling). Also, check the radio button 'Start a New Cluster' on CONFIGURE SERVER page.
This way, you will be able to successfully configure your first node.

Create Couchbase Cluster

Above step successfully launched one instance of Couchbase. To create a cluster you need to have minimum two instances of couchbase. 

Create another instance with a different name cb2. And then launch url as discussed in above step. But, be careful this time to Join a cluster (instead of start a new cluster). In the table, give your first instance IP address and then username and password.

Once, the new node is joined to the previous node your cluster is created. As, a final step go ahead and Rebalance your Couchbase to distribute data among nodes. 


---
happy learning !


Saturday, November 19, 2016

How Couchbase identifies Node for Data Access

This post talks about how Couchbase identifies where exactly the document is stored to facilitate quick read/update.

Couchbase uses a term Bucket which is equivalent to the term Database in the relational world to logically partition all documents across the cluster (or data nodes). Being a distributed DB, it tries to evenly distribute or partition (or shard) data into virtual buckets known as vBuckets. Each vbucket owns a subset of the keys or document id (and of course corresponding data as well). Documents get mapped to vBucket by applying the hash function on the key. Once the vBucket is identified there is a separate lookup table to know which node hosts the vBucket. The thing which maps different virtual buckets to nodes is known as vBucket map. (Note: Cluster Map contains the mapping of which service belong to which node at any given point of time)



Steps Involved (as shown in the diagram):
  1. Hash(key) to get vBucket identifier (vb-k) which hosts/owns Key.
  2. Looking up vBucket map tells vb-k is owned by node or server n-t
  3. The request is sent directly to the primary server node, n-t to fetch the document. 

Both hashing function as well number of vBucket is configurable. By default, Couchbase automatically divides each bucket into 1024 active vBuckets and 1024 replica buckets (per replica). When there is only one node, all vBuckets reside on that node. 

What if a new node gets added to the cluster?
When the number of nodes scales up or down the information stored in vBuckets are re-distributed among the available nodes and then the corresponding vBucket map is also updated. This entire process is known as rebalancing. Rebalancing doesn't happen automatically; as an administrator/developer you need to trigger it either from UI or through CLI.

What if the primary node is down?
All read/update request by default go to the primary node. So, if a primary node fails for some reason, Couchbase takes off that node from the cluster (if configured to do so) and promotes the replica to become the primary node. So you can fail-over to replica node manually or automatically. You can address the issue with the node, fix it and add it back to the cluster by performing rebalancing. Below table shows a sample mapping.
+------------+---------+---------+
| vbucket id | active | replica |
| 0 | node A | node B |
+------------+---------+---------+ | 1 | node B | node C |
+------------+---------+---------+
| 2 | node C | node D |
| 3 | node D | node A |


References:

---
happy learning !!!

Wednesday, November 16, 2016

Why Multi-Dimensional Scaling in Couchbase

Couchbase has been supporting horizontal scaling in a monolithic fashion since its inception. You keep adding more nodes to the cluster to scale and improve performance (all nodes being exactly the same). This single dimension scaling works to a great extent as all services - Query, Index, and Data scale at the same rate. But, they all are unique and have specific resource requirement.

Let's profile these services in detail and their specific hardware requirements to drive home the point - why MDS is required! 

This feature got added in Couchbase 4.0.


Query Service primarily executes Couchbase native queries, N1QL(similar to SQL, pronounced as nickel - leverages the flexibility of JSON and power of SQL). The query engine parses the query, generates execution plan and then executes the query in collaboration with index service and data service. The faster queries are executed, the better the performance.

Faster query processing requires more CPU or fast processor (and less memory & HDD). More cores will help in processing queries in parallel. 

Reference on  - Query Data with n1ql

Index Service performs indexing with Global Secondary Indexes (GSI - similar to B+tree used commonly in relational DBs). Index is a data structure which provides quick and efficient means to access data.  Index service creates and maintains secondary indexes and also performs an index scan for N1QL queries. GSI/indexes are global across the cluster and are defined using CREATE INDEX statement in N1QL. 

Index service is disk intensive so Optimized storage / SSD  will help in boosting performance. It needs a basic processor and less RAM/memory.  As an administrator, you can configure GSI with either the standard GSI storage, which uses ForestDB underneath (since version 4.0), for indexes that cannot fit in memory or can pick the memory optimized GSI for faster in-memory indexing and queries. 

Data Service is central for Couchbase as data is the reason for any DB.  It stores all data and handles all fetch and update requests on data.  Data service is also responsible for creating and managing MapReduce views.   Active documents that exist only on the disk take much longer to access, which creates a bottleneck for both reading and writing data. Couchbase tries to keep as much data as possible in memory.
Data refers to (document) keys, metadata, and the working set or the actual document.   Couchbase relies on extensive caching to achieve high throughput and low read/write latency. In a perfect world, all data will be sitting in memory.

Data Service: Managed Cache (based on Memcached) + Storage Engine + View Query Engine

Memory and the speed of storage device affect performance (IO operations are queued by the server so faster storage helps to drain the queue faster). 


Why MDS

So, each type of service has it's own resource constraints. Couchbase introduced multi-dimensional scaling in version 4.0 so that these services can be independently optimized and assigned the kind of hardware which will help them excel. One size fits all is not going to work (especially when you are looking for higher throughput i.e. sub-milliseconds response times).  For example, storing data and executing queries on the same node will cause CPU contention. Similarly, storing data and indexes on the same node will cause disk IO contention.

http://blog.couchbase.com/introducing-multi-dimensional-scaling

Through MDS, we can separate, isolate and scale these three services independent of each other which will improve resource utilization as well as performance.

http://developer.couchbase.com/documentation/server/4.5/concepts/distributed-data-management.html



References
http://www.couchbase.com/multi-dimensional-scalability-overview
http://developer.couchbase.com/documentation/server/4.5/concepts/distributed-data-management.html

---
happy learning !!!