Database / CouchDB Interview Questions
How does CouchDB cluster sharding work — what are the Q, n, r, and w parameters?
In a CouchDB cluster, each database is divided into Q shards (also called range partitions). The key space of document IDs is divided into Q equally-sized ranges using consistent hashing. Each shard is stored as an independent database file on a node. Each shard has n replicas — copies stored on n different nodes for fault tolerance. The default is Q=8 shards and n=3 replicas, giving 24 shard files total for a 3-node cluster.
# Create a database with 4 shards and 2 replicas
curl -X PUT "http://admin:pass@localhost:5984/mydb?q=4&n=2"
# The cluster places shard copies according to the ring
# Check shard placement:
curl http://admin:pass@localhost:5984/mydb/_shards
curl http://admin:pass@localhost:5984/mydb/_shards/doc1 # which shard holds doc1
When a client writes a document, CouchDB hashes the document's _id to determine which shard it belongs to, then writes to all n replicas of that shard. The write succeeds when w replicas acknowledge the write. When a client reads, it contacts the relevant shard replicas and returns when r replicas agree.
| Parameter | Meaning | Default |
|---|---|---|
| Q | Number of shards per database | 8 |
| n | Number of replica copies per shard | 3 |
| w | Write quorum — replicas that must acknowledge a write | 2 (majority of n=3) |
| r | Read quorum — replicas that must respond to a read | 2 |
Setting w=1 maximizes write availability at the cost of potential data loss if the one acknowledging node crashes immediately after. Setting w=n requires all replicas to be available for every write — maximum durability but reduced availability. The default majority quorum (w=2 out of n=3) is the recommended balance for most production clusters.
More Related questions...