Introduction

Scaling RDBMS

  1. Master-Slave:

    • All writes are written to the master. All reads performed against the replicated slave databases
    • Critical reads may be incorrect as writes may not have been propagated down
    • Large data sets can pose problems as the master needs to duplicate data to slaves
  2. Vertical Partitioning:

    • Have tables related to a specific feature sit on their server
    • May have to rebalance or reshard if tables outgrow the server
  3. Range-based Partitioning:

    • When a single table cannot sit on a server, split the rows (aka horizontal partitioning) of the table onto multiple servers based on some value range of a column/key
  4. Key/Hash-based Partitioning

    • Input a Key value to a Hash and use the resultant hash output as entry into multiple servers
  5. Directory-based Partitioning

    • Have a lookup service that knows the partitioning scheme
    • This allows for the adding of servers or changing of partition scheme without changing the application
  • Partition or Sharding
    • Scales well for both reads and writes
    • Not transparent; the application needs to be partition-aware
    • Can no longer have relationships/joins across partitions n Loss of referential integrity across shards

NoSQL

ACID = Atomicity, Consistency, Isolation, Durability
BASE = Basic Availability, Soft-state, Eventual consistency

  • Not Only SQL (NoSQL):

    • Class of non-relational data storage systems
    • Usually do not require a fixed table schema, nor do they use the concept of joins
  • Reasons

    1. For data storage, an RDBMS cannot be the be-all/end-all
    2. Just as there are different programming languages, there need to be other data storage tools in the toolbox
    3. A NoSQL solution is more acceptable to a client now than even a year ago

Consistency Model

A consistency model determines rules for visibility and apparent order of updates

  • For example:
    • Row X is replicated on nodes M and N
    • Client A writes row X to node N
    • Some period of time t elapses.
    • Client B reads row X from node M
    • Does client B see the write from client A?
    • Consistency is a continuum with tradeoffs
    • For NoSQL, the answer would be: maybe
      • e.g., Amazon statement of “Usually ships within 2 days” as it cannot prevent the last copy of an item to be sold multiple times

NoSQL Stores

  • Key/Value Store

    • Pros

      • very fast
      • very scalable
      • simple model
      • able to distribute horizontally
    • Cons

      • many data structures (objects) can’t be easily modeled as key value pairs
  • Schema-less

    • Pros

      • Schema-less data model is richer than key/value pairs
      • Support different type of consistency model: strict, eventual, or none
      • many are distributed
      • still provide excellent performance and scalability
    • Cons

      • typically no ACID transactions or joins
  • Common Advantages

    • Cheap, easy to implement (open source)
    • Data are replicated to multiple nodes (therefore identical and fault-tolerant) and can be partitioned
    • Easy to distribute
    • Don’t require a schema
    • Can scale up and down
    • Relax the data consistency requirement (CAP)
  • Give Up:

    • Operations like: joins, group by, order by
    • ACID transactions
    • SQL as a sometimes frustrating but still powerful query language
    • easy integration with other applications that support SQL

BigTable

A distributed storage system for managing structured data
Designed to scale to a very large size (petabytes of data across thousands of servers)
Flexible and high-performance (for all of Google’s products)

  • Motivation: Lots of (semi-)structured data (e.g., url, user data, Geographic locations) and its scale is large

  • Objective:

    1. Want access to most current data at any time
    2. Very high read/write rates
    3. Efficient scans over all
    4. Efficient joins of large one-to-one and one-to-many datasets
    5. Examine data changes over time
  • Data model
    Map indexed by a row key, column key, and a timestamp

    • Example
      • Row key: reverse URL (reverse: can easily group the webpages in the same domain)
      • Column keys: attributes of web page (Contents, and anchors that reference the page)
      • Values: contents of web pages, and other information
  • Rows

    • Each read or write of data under a single row key is atomic
    • Maintained in sorted lexicographic order (for efficient row scans)
    • Row ranges dynamically partitioned into tablets
  • Columns

    • Grouped into column families
    • Column key = family:qualifier
    • Column families provide locality hints (E.g., anchor is a column family)
    • Few column families, but unbounded number of columns
  • Timestamp

    • 64-bit integers (real time in microseconds)

Organization

  1. Google File System: The raw storage for storing logs and data files
  2. Chubby: A distributed lock manager to keep replicas consists in presence of failures
  3. SSTable: A file format for storing BigTable data
  • SSTable

    • Persistent, ordered (the keys and values within the SSTable are stored) immutable (unmodifiable, cannot change the content in the table) map from keys to values, the index traced the key range
    • Sequence of blocks on disk plus an index for block lookup (for chasing design: sorted + range traced which can easily be chased efficiently BFI search)
  • Tablet

    • Multiple SSTables group together and build a Tablet
    • Dynamically partitioned range of rows
  • Table

    • Multiple tablets make up the table, SSTables can be shared (see fig.)

Architecture

Single-master, distributed storage architecture

  • BigTable master

    • Assigns tablets to tablet servers
    • Detects addition and expiration of tablet servers
    • Balances tablet server load
    • Handles garbage collection
    • Handles schema changes
  • Tablet servers

    • Each tablet server manages a set of tablets
      • Typically between ten to a thousand tablets (each 100-200 MB by default)
    • Handles read and write requests to the tablets
    • Splits tablets that have grown too large
  • Tablet Location

    • Given a key, search the location of tablet that stored the key-value pair
    • Implementation: B+ Tree:

      1. 1st level: root tablet contains location of all tablets
      2. 2nd level: metadata tablet contains locations of user tablets
      3. 3rd level: user tablets
      • Example:
        Given $1\text{KB}$ ($1024 \text{bytes}$) key and $128\text{MB}$ ($128 \times 2^{20} \text{bytes}$) tablet size.
        Qs: how much data it can index at the 1st level: $2^{27} / 2^{10} = 2^{17}$ keys to meta-data tablets
        Qs: how many user tablet that can be represented at the 2nd level: $2^{17} \times 2^{17} = 2^{34}$ keys to user tablets
        Qs: # key-value pair that can be represented: $2^{34} \times 2^{27} = 2^{61} \text{bytes}$ data (2048 petabytes)

Operations

  • Tablet Serving

    1. Write

      1. Updates committed to a commit log
      2. Recently committed updates are stored in memtable (The data will first store in the memtable until it’s full)
      3. Older updates are stored in a sequence of SSTables (It would be pushed into the SSTable Files with sorting process)
    2. Read

      1. form a merged view of SSTables and memtable
      2. read <key-value> pair
  • Compaction (Update)

    • Minor compaction
      • Converts the memtable into an SSTable
      • Reduces memory usage and log traffic on restart
    • Merging compaction
      • Reads the contents of a few SSTables and the memtable, and writes out a new SSTable
      • Reduces number of SSTables
    • Major compaction
      • Merging compaction that results in only one SSTable
      • No deletion records, only live data

HBase

A distributed data store that can scale horizontally to 1,000s of commodity servers and petabytes of indexed storage
Designed to operate on top of the Hadoop distributed file system for scalability, fault tolerance, and high availability

Storage Model

  • Partitioning

    • A Table is horizontally partitioned into Regions, each region is composed of sequential range of keys
    • Each region is managed by a RegionServer
  • Persistence and Data availability

    • HBase stores its data in HDFS, it does NOT replicate RegionServers and relies on HDFS replication for Data Availability
    • Region data is cached in-memory

Architecture

  • Overview

  • Detailed view

  • Design
    HFile: Everything is managed in HFile, the actual storage file stored in HDFS, created to store HBase’s data fast and efficiently

    Key value pair in low level byte array

Log Replay

  • After recovery from failure, or upon bootup (HRegionServer/HMaster)
    • Replay any stale logs (use timestamps to find out where the database is w.r.t. the logs)
    • Replay: add edits to the MemStore
  • Keeps one HLog per HRegionServer rather than per region

Characteristics

  • HBase is distributed and column-oriented (data is stored by columns)
  • Tables have one primary index, the row key
  • Scans and queries can select a subset of available columns, perhaps by using a wildcard
  • Limited atomicity and transaction support
  • No accessed or manipulated via SQL

Why HBase

  • Reasons

    • HBase is a Bigtable clone
    • It is open source
    • It has a good community and promise for the future
    • It is developed on top of and has good integration for the Hadoop platform, if you are using Hadoop already
    • It has a Cascading connector
  • Benefits over RDBMS

    1. No real indexes
    2. Automatic partitioning
    3. Scale linearly and automatically with new nodes
    4. Commodity hardware
    5. Fault tolerance
    6. Batch processing
    • RDBMS is fixed-schema and row-oriented (data is stored by rows)

Dynamo

Introduction

  • Assumptions and Requirements:

    1. Simple query model: uniquely identified by keys (objects tend to be small)
    2. Stringent latency requirements: Want guarantees on 99.9th percentile of latency
    3. No ACID properties: Single key updates, No isolation guarantees, and Weaker consistency
  • Design Principles:

    1. Incremental scalability
      • System should be able to grow by adding a storage host (node) at a time
    2. Symmetry (mainly different from BigTable)
      • Every node has the same set of responsibilities
    3. Decentralization
      • Favor decentralized techniques over central coordinators
    4. Heterogeneity
      • Workload partitioning should be proportional to capabilities of servers

System Interface

  1. put(key, context, object)

    • key: primary key associated with data object
    • context: vector clocks (some sort of time-stamp over a distributed system) and history (needed for merging)
    • object: data to store
  2. get (key)

Architecture

Partitioning

Consider problem of data partition: Given document X, choose one of k servers to use
Suppose we use modulo hashing where servers 1, …, k

  • Methods:

    1. Place X on server i = X mod k

      • Problem: Data may not be uniformly distributed
    2. Place X on server i = hash(X) mod k

      • Problem: If a server fails or joins and different clients have different estimate of k, most entries get remapped to new nodes
  • Difficulty in changing number of caches (buckets)

Consistent Hashing

  • First map the nodes to a hash ring (starting from 0 to a maximize value in the clockwise direction and each node is located in one position in the hash ring), then map the object to the location of the hash ring to determine which node would store that object.

    • The advantage is when a new server is added, only the data of the successor node is affected
    • For example: Node 26 is added, data from node 26 is migrated to node 26 and update the routing tables
  • Properties

    1. Balance: Objects are assigned to buckets “randomly”.
    2. Monotonicity: When a bucket is added/removed, the only objects affected are those that are/were mapped to the bucket.
    3. Load: Objects are assigned to buckets evenly, even over a set of views.
    4. Spread: An object should be mapped to a small number of buckets over a set of views.
  • Replication
    Stores an object to N storage servers:

    1. 1st server is the one that is closest to h(x) in the clockwise direction, i.e., successor(h(x))
    2. N-1 more servers, who are the clockwise successors of successor(h(x)), will store a redundant copy of object x

      e.g., h(x) = 15 and N = 3, 1st copy will stored in node 20, the former copies will be stored in node 30 and 40
  • Consistency

    • Challenge:

      • To decide which storage server(s) to store a particular object, without choosing all servers.
      • Choosing all servers implies strict consistency!
    • Strict consistency:

      • Any read on a data item x returns a value corresponding to the result of the most recent write on x
  • Client-Side Consistency

    1. Strong consistency (~Strict consistency)

      • After the update reports a finished update, all subsequent access returns the updated value
    2. Eventual consistency

      • After the update reports a finished update, the system may report the old value
      • Nevertheless, the system will eventually report the updated value

Vector Clock

A Vector Clock is a list of (node, counter) pairs for tracking the partial ordering of events occurring in different nodes (processes) within a distributed system

  • Each time a node (process) experiences an internal event, it increments its own logical clock (counter) in the vector by one
  • Each time a node prepares to send out a message, it first increments its own logical counter in the vector by one before sending its entire vector along with the message being sent
  • Each time a node receives a message, it increments its own logical counter in the vector by one and then updates each element in its vector by taking the maximum of the value of its own vector clock and the value in the vector carried by the received message in an element-by-element manner

  • Version tracking

    • When a node operates on an object, every version of the object will include a copy of the node’s current vector clock values
    • If the counters on the first object’s clock are less- than-or-equal to (and not identical to) all of the nodes in a second object’s vector clock counters, then the first object is an ancestor of the second one and can be forgotten
  • Example:

    1. A client writes D1 at server SX: D1 ([SX,1])
    2. Another client reads D1, writes back D2; also handled by SX: D2 ([SX,2])
    3. Another client reads D2, writes back D3; handled by server SY: D3 ([SX,2], [SY,1])
    4. Another client reads D2, writes back D4; handled by server SZ: D4 ([SX,2], [SZ,1])
    5. Another client reads D3, D4: CONFLICT !

Data Versioning

  1. Vector Clock
    • Updates generate a new timestamp
  2. Eventual consistency
    • Multiple versions of the same object might co-exist
  3. Syntactic Reconciliation
    • System might be able to resolve conflicts automatically, e.g., Dynamo enforces last-writer-wins
  4. Semantic Reconciliation
    • conflict resolution pushed to application, e.g., merge conflicting shopping carts
  • Quantifying
    In a 24 hour trace
    • 99.94% of requests saw exactly one version
    • 0.00057% received 2 versions
    • 0.00047% received 3 versions
    • 0.00009% received 4 versions

Temporary Failures

  • Configurable parameters

    1. N = the number of nodes that store replicas of the data
    2. W [1, N] = the number of replicas that need to acknowledge the receipt of update
    3. R [1, N] (read) = the number of replicas that are contacted when a data object is accessed, because there are a chance that some replicas may not been updated (choose the latest version)
    • If W + R > N, then it is strong consistency

      • e.g., If N = 3, W = 2, and R = 2, what may happen?
      • If N = 3, W = 2, R = 2, at least 2 out of 3 replicas are acknowledged during writing. Regardless which 2 replicas be read, have at least 1 server that overlaps with write that have received the acknowledgement. So it can ensure that user must read the latest replica (ensure at least one of the reading server have received the acknowledgement).
    • If W + R <= N, then it is eventual consistency

      • e.g., If N = 3, W = 2, and R = 1
    • Dynamo’s Setting: Common (N,R,W) in Dynamo: (3,2,2)

  • Partitions Handling
    • Sloppy quorum
      All reads/writes are performed on the first N healthy nodes from the preference list, which may not always be the first N nodes in the consistent hashing ring, with metadata specifying that the replica should be sent to the intended recipient later e.g., if node A is down, a replica is sent to node A’
    • Hinted handoff
      • Node A’ receives a hint that the update is temporary
      • A’ sends back the replica to A if A is recovered, and removes its replica
  • Picture
    • When N20 is temporarily down or unreachable during a write, send replica to N32
    • N32 is hinted that the replica is belong to N20 and it will deliver to N20 when N20 is recovered
    • RESULTS: Dynamo is an “always writeable” data store
    • Ideally, this strategy works perfectly
      • Recall that Chord normally replicates a key-value pair on a few nodes, so we would expect to see several nodes that “know” the current mapping: a shard
      • After the intended target recovers the repair code will bring it back up to date by copying key-value tuples

Permanent Failures

Use Merkle Trees to speed-up detection of inconsistencies between data stored by replicas

  • Anti-Entropy operations: actively compared the content of different replicas and update all copies to the latest version

Cluster Membership & Failure Detection

System state disseminated via Gossiping in O(logN) rounds where N = # of nodes in the cluster

  • Every T seconds each member increments its heartbeat counter and selects one other member to send its list to
  • A member merges the list with its own list

Conclusion

Problem Technique Advantage
Partitioning Consistent Hashing Incremental Scalability
High Availability for writes Vector clocks with reconciliation during reads Version size is decoupled from update rates.
Handling temporary failures Sloppy Quorum and hinted handoff Provides high availability and durability guarantee when some of the replicas are not available.
Recovering from permanent failures Anti-entropy using Merkle trees Synchronizes divergent replicas in the background.
Membership and failure detection Gossip-based membership protocol and failure detection Preserves symmetry and avoids having a centralized registry for storing membership and node liveness information.

Cassandra

Design Goals

  1. High availability
  2. Eventual consistency
  3. Incremental scalability
  4. Optimistic Replication
  5. “Knobs” to tune tradeoffs between consistency, durability and latency
  6. Low total cost of ownership
  7. Minimal administration

Operations

  • Write Operation

    • A client issues a write request to a random node in the Cassandra cluster.
    • The “Partitioner” determines the nodes responsible for the data.
    • Locally, write operations are logged and then applied to an in-memory version.
    • Commit log is stored on a dedicated disk local to the machine.
  • Write Properties

    • No locks in the critical path
    • Sequential disk access
    • Behaves like a write back Cache
    • Append support without read ahead n Atomicity guarantee for a key
    • “Always Writable” (accept writes during failure scenarios)
  • Delete Operation: don’t delete item right away

    • Add a tombstone to the log
    • Compaction will eventually remove tombstone and delete item
  • Read Operation: Similar to writes, except

    • Coordinator can contact a number of replicas (e.g., in same rack) specified by consistency level
    • Coordinator also fetches value from multiple replicas
    • A row may be split across multiple SSTables => reads need to touch multiple SSTables => reads slower than writes (but still fast)

Quorums

  • Reads (R)

    • Wait for R replicas (R specified by clients)
    • In the background, check for consistency of remaining N-R replicas, and initiate read repair if needed
  • Writes (R)

    • come in two default flavors n Block until quorum is reached
    • Async: Write to any node
  • If W+R > N, you have consistency, i.e., each read returns the latest written value

Consistency

  • Read Consistency Levels

  • Write Consistency Levels

  • Eventual Consistency

    • If all writers stop (to a key), then all its values (replicas) will converge eventually
    • If writes continue, then system always tries to keep converging
      • Converges when R + W > N
    • Converges when R + W > N:
      • ONE: R or W is 1
      • QUORUM: R or W is ceiling (N+1)/2
      • ALL: R or W is N
    • If you want to write with Consistency Level of ONE and get the same data when you read, you need to read with Consistency Level of ALL