4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
29 :source-language: java
34 [[arch.overview.nosql]]
37 HBase is a type of "NoSQL" database.
38 "NoSQL" is a general term meaning that the database isn't an RDBMS which supports SQL as its primary access language, but there are many types of NoSQL databases: BerkeleyDB is an example of a local NoSQL database, whereas HBase is very much a distributed database.
39 Technically speaking, HBase is really more a "Data Store" than "Data Base" because it lacks many of the features you find in an RDBMS, such as typed columns, secondary indexes, triggers, and advanced query languages, etc.
41 However, HBase has many features which supports both linear and modular scaling.
42 HBase clusters expand by adding RegionServers that are hosted on commodity class servers.
43 If a cluster expands from 10 to 20 RegionServers, for example, it doubles both in terms of storage and as well as processing capacity.
44 An RDBMS can scale well, but only up to a point - specifically, the size of a single database
45 server - and for the best performance requires specialized hardware and storage devices.
46 HBase features of note are:
48 * Strongly consistent reads/writes: HBase is not an "eventually consistent" DataStore.
49 This makes it very suitable for tasks such as high-speed counter aggregation.
50 * Automatic sharding: HBase tables are distributed on the cluster via regions, and regions are automatically split and re-distributed as your data grows.
51 * Automatic RegionServer failover
52 * Hadoop/HDFS Integration: HBase supports HDFS out of the box as its distributed file system.
53 * MapReduce: HBase supports massively parallelized processing via MapReduce for using HBase as both source and sink.
54 * Java Client API: HBase supports an easy to use Java API for programmatic access.
55 * Thrift/REST API: HBase also supports Thrift and REST for non-Java front-ends.
56 * Block Cache and Bloom Filters: HBase supports a Block Cache and Bloom Filters for high volume query optimization.
57 * Operational Management: HBase provides build-in web-pages for operational insight as well as JMX metrics.
59 [[arch.overview.when]]
60 === When Should I Use HBase?
62 HBase isn't suitable for every problem.
64 First, make sure you have enough data.
65 If you have hundreds of millions or billions of rows, then HBase is a good candidate.
66 If you only have a few thousand/million rows, then using a traditional RDBMS might be a better choice due to the fact that all of your data might wind up on a single node (or two) and the rest of the cluster may be sitting idle.
68 Second, make sure you can live without all the extra features that an RDBMS provides (e.g., typed columns, secondary indexes, transactions, advanced query languages, etc.) An application built against an RDBMS cannot be "ported" to HBase by simply changing a JDBC driver, for example.
69 Consider moving from an RDBMS to HBase as a complete redesign as opposed to a port.
71 Third, make sure you have enough hardware.
72 Even HDFS doesn't do well with anything less than 5 DataNodes (due to things such as HDFS block replication which has a default of 3), plus a NameNode.
74 HBase can run quite well stand-alone on a laptop - but this should be considered a development configuration only.
76 [[arch.overview.hbasehdfs]]
77 === What Is The Difference Between HBase and Hadoop/HDFS?
79 link:https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html[HDFS] is a distributed file system that is well suited for the storage of large files.
80 Its documentation states that it is not, however, a general purpose file system, and does not provide fast individual record lookups in files.
81 HBase, on the other hand, is built on top of HDFS and provides fast record lookups (and updates) for large tables.
82 This can sometimes be a point of conceptual confusion.
83 HBase internally puts your data in indexed "StoreFiles" that exist on HDFS for high-speed lookups.
84 See the <<datamodel>> and the rest of this chapter for more information on how HBase achieves its goals.
89 The catalog table `hbase:meta` exists as an HBase table and is filtered out of the HBase shell's `list` command, but is in fact a table just like any other.
94 The `hbase:meta` table (previously called `.META.`) keeps a list of all regions in the system, and the location of `hbase:meta` is stored in ZooKeeper.
96 The `hbase:meta` table structure is as follows:
100 * Region key of the format (`[table],[region start key],[region id]`)
104 * `info:regioninfo` (serialized link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/HRegionInfo.html[HRegionInfo] instance for this region)
105 * `info:server` (server:port of the RegionServer containing this region)
106 * `info:serverstartcode` (start-time of the RegionServer process containing this region)
108 When a table is in the process of splitting, two other columns will be created, called `info:splitA` and `info:splitB`.
109 These columns represent the two daughter regions.
110 The values for these columns are also serialized HRegionInfo instances.
111 After the region has been split, eventually this row will be deleted.
116 The empty key is used to denote table start and table end.
117 A region with an empty start key is the first region in a table.
118 If a region has both an empty start and an empty end key, it is the only region in the table
121 In the (hopefully unlikely) event that programmatic processing of catalog metadata
122 is required, see the link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/client/RegionInfo.html#parseFrom-byte:A-[RegionInfo.parseFrom] utility.
124 [[arch.catalog.startup]]
125 === Startup Sequencing
127 First, the location of `hbase:meta` is looked up in ZooKeeper.
128 Next, `hbase:meta` is updated with server and startcode values.
130 For information on region-RegionServer assignment, see <<regions.arch.assignment>>.
132 [[architecture.client]]
135 The HBase client finds the RegionServers that are serving the particular row range of interest.
136 It does this by querying the `hbase:meta` table.
137 See <<arch.catalog.meta>> for details.
138 After locating the required region(s), the client contacts the RegionServer serving that region, rather than going through the master, and issues the read or write request.
139 This information is cached in the client so that subsequent requests need not go through the lookup process.
140 Should a region be reassigned either by the master load balancer or because a RegionServer has died, the client will requery the catalog tables to determine the new location of the user region.
142 See <<master.runtime>> for more information about the impact of the Master on HBase Client communication.
144 Administrative functions are done via an instance of link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Admin.html[Admin]
146 [[client.connections]]
147 === Cluster Connections
149 The API changed in HBase 1.0. For connection configuration information, see <<client_dependencies>>.
151 ==== API as of HBase 1.0.0
153 It's been cleaned up and users are returned Interfaces to work against rather than particular types.
154 In HBase 1.0, obtain a `Connection` object from `ConnectionFactory` and thereafter, get from it instances of `Table`, `Admin`, and `RegionLocator` on an as-need basis.
155 When done, close the obtained instances.
156 Finally, be sure to cleanup your `Connection` instance before exiting.
157 `Connections` are heavyweight objects but thread-safe so you can create one for your application and keep the instance around.
158 `Table`, `Admin` and `RegionLocator` instances are lightweight.
159 Create as you go and then let go as soon as you are done by closing them.
160 See the link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/package-summary.html[Client Package Javadoc Description] for example usage of the new HBase 1.0 API.
162 ==== API before HBase 1.0.0
164 Instances of `HTable` are the way to interact with an HBase cluster earlier than 1.0.0. _link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Table.html[Table] instances are not thread-safe_. Only one thread can use an instance of Table at any given time.
165 When creating Table instances, it is advisable to use the same link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/HBaseConfiguration[HBaseConfiguration] instance.
166 This will ensure sharing of ZooKeeper and socket instances to the RegionServers which is usually what you want.
167 For example, this is preferred:
171 HBaseConfiguration conf = HBaseConfiguration.create();
172 HTable table1 = new HTable(conf, "myTable");
173 HTable table2 = new HTable(conf, "myTable");
180 HBaseConfiguration conf1 = HBaseConfiguration.create();
181 HTable table1 = new HTable(conf1, "myTable");
182 HBaseConfiguration conf2 = HBaseConfiguration.create();
183 HTable table2 = new HTable(conf2, "myTable");
186 For more information about how connections are handled in the HBase client, see link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/ConnectionFactory.html[ConnectionFactory].
188 [[client.connection.pooling]]
189 ===== Connection Pooling
191 For applications which require high-end multithreaded access (e.g., web-servers or application servers that may serve many application threads in a single JVM), you can pre-create a `Connection`, as shown in the following example:
193 .Pre-Creating a `Connection`
197 // Create a connection to the cluster.
198 Configuration conf = HBaseConfiguration.create();
199 try (Connection connection = ConnectionFactory.createConnection(conf);
200 Table table = connection.getTable(TableName.valueOf(tablename))) {
201 // use table as needed, the table returned is lightweight
206 .`HTablePool` is Deprecated
209 Previous versions of this guide discussed `HTablePool`, which was deprecated in HBase 0.94, 0.95, and 0.96, and removed in 0.98.1, by link:https://issues.apache.org/jira/browse/HBASE-6580[HBASE-6580], or `HConnection`, which is deprecated in HBase 1.0 by `Connection`.
210 Please use link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Connection.html[Connection] instead.
213 [[client.writebuffer]]
214 === WriteBuffer and Batch Methods
216 In HBase 1.0 and later, link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/client/HTable.html[HTable] is deprecated in favor of link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Table.html[Table]. `Table` does not use autoflush. To do buffered writes, use the BufferedMutator class.
218 In HBase 2.0 and later, link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/client/HTable.html[HTable] does not use BufferedMutator to execute the ``Put`` operation. Refer to link:https://issues.apache.org/jira/browse/HBASE-18500[HBASE-18500] for more information.
220 For additional information on write durability, review the link:/acid-semantics.html[ACID semantics] page.
222 For fine-grained control of batching of ``Put``s or ``Delete``s, see the link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Table.html#batch-java.util.List-java.lang.Object:A-[batch] methods on Table.
225 === Asynchronous Client ===
227 It is a new API introduced in HBase 2.0 which aims to provide the ability to access HBase asynchronously.
229 You can obtain an `AsyncConnection` from `ConnectionFactory`, and then get a asynchronous table instance from it to access HBase. When done, close the `AsyncConnection` instance(usually when your program exits).
231 For the asynchronous table, most methods have the same meaning with the old `Table` interface, expect that the return value is wrapped with a CompletableFuture usually. We do not have any buffer here so there is no close method for asynchronous table, you do not need to close it. And it is thread safe.
233 There are several differences for scan:
235 * There is still a `getScanner` method which returns a `ResultScanner`. You can use it in the old way and it works like the old `ClientAsyncPrefetchScanner`.
236 * There is a `scanAll` method which will return all the results at once. It aims to provide a simpler way for small scans which you want to get the whole results at once usually.
237 * The Observer Pattern. There is a scan method which accepts a `ScanResultConsumer` as a parameter. It will pass the results to the consumer.
239 Notice that `AsyncTable` interface is templatized. The template parameter specifies the type of `ScanResultConsumerBase` used by scans, which means the observer style scan APIs are different. The two types of scan consumers are - `ScanResultConsumer` and `AdvancedScanResultConsumer`.
241 `ScanResultConsumer` needs a separate thread pool which is used to execute the callbacks registered to the returned CompletableFuture. Because the use of separate thread pool frees up RPC threads, callbacks are free to do anything. Use this if the callbacks are not quick, or when in doubt.
243 `AdvancedScanResultConsumer` executes callbacks inside the framework thread. It is not allowed to do time consuming work in the callbacks else it will likely block the framework threads and cause very bad performance impact. As its name, it is designed for advanced users who want to write high performance code. See `org.apache.hadoop.hbase.client.example.HttpProxyExample` for how to write fully asynchronous code with it.
246 === Asynchronous Admin ===
248 You can obtain an `AsyncConnection` from `ConnectionFactory`, and then get a `AsyncAdmin` instance from it to access HBase. Notice that there are two `getAdmin` methods to get a `AsyncAdmin` instance. One method has one extra thread pool parameter which is used to execute callbacks. It is designed for normal users. Another method doesn't need a thread pool and all the callbacks are executed inside the framework thread so it is not allowed to do time consuming works in the callbacks. It is designed for advanced users.
250 The default `getAdmin` methods will return a `AsyncAdmin` instance which use default configs. If you want to customize some configs, you can use `getAdminBuilder` methods to get a `AsyncAdminBuilder` for creating `AsyncAdmin` instance. Users are free to only set the configs they care about to create a new `AsyncAdmin` instance.
252 For the `AsyncAdmin` interface, most methods have the same meaning with the old `Admin` interface, expect that the return value is wrapped with a CompletableFuture usually.
254 For most admin operations, when the returned CompletableFuture is done, it means the admin operation has also been done. But for compact operation, it only means the compact request was sent to HBase and may need some time to finish the compact operation. For `rollWALWriter` method, it only means the rollWALWriter request was sent to the region server and may need some time to finish the `rollWALWriter` operation.
256 For region name, we only accept `byte[]` as the parameter type and it may be a full region name or a encoded region name. For server name, we only accept `ServerName` as the parameter type. For table name, we only accept `TableName` as the parameter type. For `list*` operations, we only accept `Pattern` as the parameter type if you want to do regex matching.
261 Information on non-Java clients and custom protocols is covered in <<external_apis>>
264 == Client Request Filters
266 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Get.html[Get] and link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Scan.html[Scan] instances can be optionally configured with link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/Filter.html[filters] which are applied on the RegionServer.
268 Filters can be confusing because there are many different types, and it is best to approach them by understanding the groups of Filter functionality.
270 [[client.filter.structural]]
273 Structural Filters contain other Filters.
275 [[client.filter.structural.fl]]
278 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FilterList.html[FilterList] represents a list of Filters with a relationship of `FilterList.Operator.MUST_PASS_ALL` or `FilterList.Operator.MUST_PASS_ONE` between the Filters.
279 The following example shows an 'or' between two Filters (checking for either 'my value' or 'my other value' on the same attribute).
283 FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ONE);
284 SingleColumnValueFilter filter1 = new SingleColumnValueFilter(
287 CompareOperator.EQUAL,
288 Bytes.toBytes("my value")
291 SingleColumnValueFilter filter2 = new SingleColumnValueFilter(
294 CompareOperator.EQUAL,
295 Bytes.toBytes("my other value")
298 scan.setFilter(list);
304 [[client.filter.cv.scvf]]
305 ==== SingleColumnValueFilter
307 A SingleColumnValueFilter (see:
308 https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/SingleColumnValueFilter.html)
309 can be used to test column values for equivalence (`CompareOperaor.EQUAL`),
310 inequality (`CompareOperaor.NOT_EQUAL`), or ranges (e.g., `CompareOperaor.GREATER`). The following is an
311 example of testing equivalence of a column to a String value "my value"...
315 SingleColumnValueFilter filter = new SingleColumnValueFilter(
318 CompareOperaor.EQUAL,
319 Bytes.toBytes("my value")
321 scan.setFilter(filter);
324 [[client.filter.cv.cvf]]
325 ==== ColumnValueFilter
327 Introduced in HBase-2.0.0 version as a complementation of SingleColumnValueFilter, ColumnValueFilter
328 gets matched cell only, while SingleColumnValueFilter gets the entire row
329 (has other columns and values) to which the matched cell belongs. Parameters of constructor of
330 ColumnValueFilter are the same as SingleColumnValueFilter.
333 ColumnValueFilter filter = new ColumnValueFilter(
336 CompareOperaor.EQUAL,
337 Bytes.toBytes("my value")
339 scan.setFilter(filter);
342 Note. For simple query like "equals to a family:qualifier:value", we highly recommend to use the
343 following way instead of using SingleColumnValueFilter or ColumnValueFilter:
346 Scan scan = new Scan();
347 scan.addColumn(Bytes.toBytes("family"), Bytes.toBytes("qualifier"));
348 ValueFilter vf = new ValueFilter(CompareOperator.EQUAL,
349 new BinaryComparator(Bytes.toBytes("value")));
353 This scan will restrict to the specified column 'family:qualifier', avoiding scan unrelated
354 families and columns, which has better performance, and `ValueFilter` is the condition used to do
357 But if query is much more complicated beyond this book, then please make your good choice case by case.
359 [[client.filter.cvp]]
360 === Column Value Comparators
362 There are several Comparator classes in the Filter package that deserve special mention.
363 These Comparators are used in concert with other Filters, such as <<client.filter.cv.scvf>>.
365 [[client.filter.cvp.rcs]]
366 ==== RegexStringComparator
368 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/RegexStringComparator.html[RegexStringComparator] supports regular expressions for value comparisons.
372 RegexStringComparator comp = new RegexStringComparator("my."); // any value that starts with 'my'
373 SingleColumnValueFilter filter = new SingleColumnValueFilter(
376 CompareOperaor.EQUAL,
379 scan.setFilter(filter);
382 See the Oracle JavaDoc for link:http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html[supported RegEx patterns in Java].
384 [[client.filter.cvp.substringcomparator]]
385 ==== SubstringComparator
387 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/SubstringComparator.html[SubstringComparator] can be used to determine if a given substring exists in a value.
388 The comparison is case-insensitive.
393 SubstringComparator comp = new SubstringComparator("y val"); // looking for 'my value'
394 SingleColumnValueFilter filter = new SingleColumnValueFilter(
397 CompareOperaor.EQUAL,
400 scan.setFilter(filter);
403 [[client.filter.cvp.bfp]]
404 ==== BinaryPrefixComparator
406 See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/BinaryPrefixComparator.html[BinaryPrefixComparator].
408 [[client.filter.cvp.bc]]
409 ==== BinaryComparator
411 See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/BinaryComparator.html[BinaryComparator].
413 [[client.filter.kvm]]
414 === KeyValue Metadata
416 As HBase stores data internally as KeyValue pairs, KeyValue Metadata Filters evaluate the existence of keys (i.e., ColumnFamily:Column qualifiers) for a row, as opposed to values the previous section.
418 [[client.filter.kvm.ff]]
421 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FamilyFilter.html[FamilyFilter] can be used to filter on the ColumnFamily.
422 It is generally a better idea to select ColumnFamilies in the Scan than to do it with a Filter.
424 [[client.filter.kvm.qf]]
427 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/QualifierFilter.html[QualifierFilter] can be used to filter based on Column (aka Qualifier) name.
429 [[client.filter.kvm.cpf]]
430 ==== ColumnPrefixFilter
432 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/ColumnPrefixFilter.html[ColumnPrefixFilter] can be used to filter based on the lead portion of Column (aka Qualifier) names.
434 A ColumnPrefixFilter seeks ahead to the first column matching the prefix in each row and for each involved column family.
435 It can be used to efficiently get a subset of the columns in very wide rows.
437 Note: The same column qualifier can be used in different column families.
438 This filter returns all matching columns.
440 Example: Find all columns in a row and family that start with "abc"
447 byte[] prefix = Bytes.toBytes("abc");
448 Scan scan = new Scan(row, row); // (optional) limit to one row
449 scan.addFamily(family); // (optional) limit to one family
450 Filter f = new ColumnPrefixFilter(prefix);
452 scan.setBatch(10); // set this if there could be many columns returned
453 ResultScanner rs = t.getScanner(scan);
454 for (Result r = rs.next(); r != null; r = rs.next()) {
455 for (KeyValue kv : r.raw()) {
456 // each kv represents a column
462 [[client.filter.kvm.mcpf]]
463 ==== MultipleColumnPrefixFilter
465 link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/MultipleColumnPrefixFilter.html[MultipleColumnPrefixFilter] behaves like ColumnPrefixFilter but allows specifying multiple prefixes.
467 Like ColumnPrefixFilter, MultipleColumnPrefixFilter efficiently seeks ahead to the first column matching the lowest prefix and also seeks past ranges of columns between prefixes.
468 It can be used to efficiently get discontinuous sets of columns from very wide rows.
470 Example: Find all columns in a row and family that start with "abc" or "xyz"
477 byte[][] prefixes = new byte[][] {Bytes.toBytes("abc"), Bytes.toBytes("xyz")};
478 Scan scan = new Scan(row, row); // (optional) limit to one row
479 scan.addFamily(family); // (optional) limit to one family
480 Filter f = new MultipleColumnPrefixFilter(prefixes);
482 scan.setBatch(10); // set this if there could be many columns returned
483 ResultScanner rs = t.getScanner(scan);
484 for (Result r = rs.next(); r != null; r = rs.next()) {
485 for (KeyValue kv : r.raw()) {
486 // each kv represents a column
492 [[client.filter.kvm.crf]]
493 ==== ColumnRangeFilter
495 A link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/ColumnRangeFilter.html[ColumnRangeFilter] allows efficient intra row scanning.
497 A ColumnRangeFilter can seek ahead to the first matching column for each involved column family.
498 It can be used to efficiently get a 'slice' of the columns of a very wide row.
500 you have a million columns in a row but you only want to look at columns bbbb-bbdd.
502 Note: The same column qualifier can be used in different column families.
503 This filter returns all matching columns.
505 Example: Find all columns in a row and family between "bbbb" (inclusive) and "bbdd" (inclusive)
512 byte[] startColumn = Bytes.toBytes("bbbb");
513 byte[] endColumn = Bytes.toBytes("bbdd");
514 Scan scan = new Scan(row, row); // (optional) limit to one row
515 scan.addFamily(family); // (optional) limit to one family
516 Filter f = new ColumnRangeFilter(startColumn, true, endColumn, true);
518 scan.setBatch(10); // set this if there could be many columns returned
519 ResultScanner rs = t.getScanner(scan);
520 for (Result r = rs.next(); r != null; r = rs.next()) {
521 for (KeyValue kv : r.raw()) {
522 // each kv represents a column
528 Note: Introduced in HBase 0.92
530 [[client.filter.row]]
533 [[client.filter.row.rf]]
536 It is generally a better idea to use the startRow/stopRow methods on Scan for row selection, however link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/RowFilter.html[RowFilter] can also be used.
538 [[client.filter.utility]]
541 [[client.filter.utility.fkof]]
542 ==== FirstKeyOnlyFilter
544 This is primarily used for rowcount jobs.
545 See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FirstKeyOnlyFilter.html[FirstKeyOnlyFilter].
547 [[architecture.master]]
550 `HMaster` is the implementation of the Master Server.
551 The Master server is responsible for monitoring all RegionServer instances in the cluster, and is the interface for all metadata changes.
552 In a distributed cluster, the Master typically runs on the <<arch.hdfs.nn>>.
553 J Mohamed Zahoor goes into some more detail on the Master Architecture in this blog posting, link:http://blog.zahoor.in/2012/08/hbase-hmaster-architecture/[HBase HMaster Architecture ].
558 If run in a multi-Master environment, all Masters compete to run the cluster.
559 If the active Master loses its lease in ZooKeeper (or the Master shuts down), then the remaining Masters jostle to take over the Master role.
564 A common dist-list question involves what happens to an HBase cluster when the Master goes down.
565 Because the HBase client talks directly to the RegionServers, the cluster can still function in a "steady state". Additionally, per <<arch.catalog>>, `hbase:meta` exists as an HBase table and is not resident in the Master.
566 However, the Master controls critical functions such as RegionServer failover and completing region splits.
567 So while the cluster can still run for a short time without the Master, the Master should be restarted as soon as possible.
572 The methods exposed by `HMasterInterface` are primarily metadata-oriented methods:
574 * Table (createTable, modifyTable, removeTable, enable, disable)
575 * ColumnFamily (addColumn, modifyColumn, removeColumn)
576 * Region (move, assign, unassign) For example, when the `Admin` method `disableTable` is invoked, it is serviced by the Master server.
581 The Master runs several background threads:
583 [[master.processes.loadbalancer]]
586 Periodically, and when there are no regions in transition, a load balancer will run and move regions around to balance the cluster's load.
587 See <<balancer_config>> for configuring this property.
589 See <<regions.arch.assignment>> for more information on region assignment.
591 [[master.processes.catalog]]
594 Periodically checks and cleans up the `hbase:meta` table.
595 See <<arch.catalog.meta>> for more information on the meta table.
597 [[regionserver.arch]]
600 `HRegionServer` is the RegionServer implementation.
601 It is responsible for serving and managing regions.
602 In a distributed cluster, a RegionServer runs on a <<arch.hdfs.dn>>.
604 [[regionserver.arch.api]]
607 The methods exposed by `HRegionRegionInterface` contain both data-oriented and region-maintenance methods:
609 * Data (get, put, delete, next, etc.)
610 * Region (splitRegion, compactRegion, etc.) For example, when the `Admin` method `majorCompact` is invoked on a table, the client is actually iterating through all regions for the specified table and requesting a major compaction directly to each region.
612 [[regionserver.arch.processes]]
615 The RegionServer runs a variety of background threads:
617 [[regionserver.arch.processes.compactsplit]]
618 ==== CompactSplitThread
620 Checks for splits and handle minor compactions.
622 [[regionserver.arch.processes.majorcompact]]
623 ==== MajorCompactionChecker
625 Checks for major compactions.
627 [[regionserver.arch.processes.memstore]]
630 Periodically flushes in-memory writes in the MemStore to StoreFiles.
632 [[regionserver.arch.processes.log]]
635 Periodically checks the RegionServer's WAL.
639 Coprocessors were added in 0.92.
640 There is a thorough link:https://blogs.apache.org/hbase/entry/coprocessor_introduction[Blog Overview of CoProcessors] posted.
641 Documentation will eventually move to this reference guide, but the blog is the most current information available at this time.
646 HBase provides two different BlockCache implementations: the default on-heap `LruBlockCache` and the `BucketCache`, which is (usually) off-heap.
647 This section discusses benefits and drawbacks of each implementation, how to choose the appropriate option, and configuration options for each.
649 .Block Cache Reporting: UI
652 See the RegionServer UI for detail on caching deploy.
653 Since HBase 0.98.4, the Block Cache detail has been significantly extended showing configurations, sizings, current usage, time-in-the-cache, and even detail on block counts and types.
658 `LruBlockCache` is the original implementation, and is entirely within the Java heap. `BucketCache` is mainly intended for keeping block cache data off-heap, although `BucketCache` can also keep data on-heap and serve from a file-backed cache.
660 .BucketCache is production ready as of HBase 0.98.6
663 To run with BucketCache, you need HBASE-11678.
664 This was included in 0.98.6.
667 Fetching will always be slower when fetching from BucketCache, as compared to the native on-heap LruBlockCache.
668 However, latencies tend to be less erratic across time, because there is less garbage collection when you use BucketCache since it is managing BlockCache allocations, not the GC.
669 If the BucketCache is deployed in off-heap mode, this memory is not managed by the GC at all.
670 This is why you'd use BucketCache, so your latencies are less erratic and to mitigate GCs and heap fragmentation.
671 See Nick Dimiduk's link:http://www.n10k.com/blog/blockcache-101/[BlockCache 101] for comparisons running on-heap vs off-heap tests.
672 Also see link:https://people.apache.org/~stack/bc/[Comparing BlockCache Deploys] which finds that if your dataset fits inside your LruBlockCache deploy, use it otherwise if you are experiencing cache churn (or you want your cache to exist beyond the vagaries of java GC), use BucketCache.
674 When you enable BucketCache, you are enabling a two tier caching system, an L1 cache which is implemented by an instance of LruBlockCache and an off-heap L2 cache which is implemented by BucketCache.
675 Management of these two tiers and the policy that dictates how blocks move between them is done by `CombinedBlockCache`.
676 It keeps all DATA blocks in the L2 BucketCache and meta blocks -- INDEX and BLOOM blocks -- on-heap in the L1 `LruBlockCache`.
677 See <<offheap.blockcache>> for more detail on going off-heap.
679 [[cache.configurations]]
680 ==== General Cache Configurations
682 Apart from the cache implementation itself, you can set some general configuration options to control how the cache performs.
683 See https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html.
684 After setting any of these options, restart or rolling restart your cluster for the configuration to take effect.
685 Check logs for errors or unexpected behavior.
687 See also <<blockcache.prefetch>>, which discusses a new option introduced in link:https://issues.apache.org/jira/browse/HBASE-9857[HBASE-9857].
689 [[block.cache.design]]
690 ==== LruBlockCache Design
692 The LruBlockCache is an LRU cache that contains three levels of block priority to allow for scan-resistance and in-memory ColumnFamilies:
694 * Single access priority: The first time a block is loaded from HDFS it normally has this priority and it will be part of the first group to be considered during evictions.
695 The advantage is that scanned blocks are more likely to get evicted than blocks that are getting more usage.
696 * Multi access priority: If a block in the previous priority group is accessed again, it upgrades to this priority.
697 It is thus part of the second group considered during evictions.
698 * In-memory access priority: If the block's family was configured to be "in-memory", it will be part of this priority disregarding the number of times it was accessed.
699 Catalog tables are configured like this.
700 This group is the last one considered during evictions.
702 To mark a column family as in-memory, call
706 HColumnDescriptor.setInMemory(true);
709 if creating a table from java, or set `IN_MEMORY => true` when creating or altering a table in the shell: e.g.
713 hbase(main):003:0> create 't', {NAME => 'f', IN_MEMORY => 'true'}
716 For more information, see the LruBlockCache source
718 [[block.cache.usage]]
719 ==== LruBlockCache Usage
721 Block caching is enabled by default for all the user tables which means that any read operation will load the LRU cache.
722 This might be good for a large number of use cases, but further tunings are usually required in order to achieve better performance.
723 An important concept is the link:http://en.wikipedia.org/wiki/Working_set_size[working set size], or WSS, which is: "the amount of memory needed to compute the answer to a problem". For a website, this would be the data that's needed to answer the queries over a short amount of time.
725 The way to calculate how much memory is available in HBase for caching is:
729 number of region servers * heap size * hfile.block.cache.size * 0.99
732 The default value for the block cache is 0.25 which represents 25% of the available heap.
733 The last value (99%) is the default acceptable loading factor in the LRU cache after which eviction is started.
734 The reason it is included in this equation is that it would be unrealistic to say that it is possible to use 100% of the available memory since this would make the process blocking from the point where it loads new blocks.
735 Here are some examples:
737 * One region server with the heap size set to 1 GB and the default block cache size will have 253 MB of block cache available.
738 * 20 region servers with the heap size set to 8 GB and a default block cache size will have 39.6 of block cache.
739 * 100 region servers with the heap size set to 24 GB and a block cache size of 0.5 will have about 1.16 TB of block cache.
741 Your data is not the only resident of the block cache.
742 Here are others that you may have to take into account:
745 The `hbase:meta` table is forced into the block cache and have the in-memory priority which means that they are harder to evict.
747 NOTE: The hbase:meta tables can occupy a few MBs depending on the number of regions.
750 An _HFile_ is the file format that HBase uses to store data in HDFS.
751 It contains a multi-layered index which allows HBase to seek to the data without having to read the whole file.
752 The size of those indexes is a factor of the block size (64KB by default), the size of your keys and the amount of data you are storing.
753 For big data sets it's not unusual to see numbers around 1GB per region server, although not all of it will be in cache because the LRU will evict indexes that aren't used.
756 The values that are stored are only half the picture, since each value is stored along with its keys (row key, family qualifier, and timestamp). See <<keysize>>.
759 Just like the HFile indexes, those data structures (when enabled) are stored in the LRU.
761 Currently the recommended way to measure HFile indexes and bloom filters sizes is to look at the region server web UI and checkout the relevant metrics.
762 For keys, sampling can be done by using the HFile command line tool and look for the average key size metric.
763 Since HBase 0.98.3, you can view details on BlockCache stats and metrics in a special Block Cache section in the UI.
765 It's generally bad to use block caching when the WSS doesn't fit in memory.
766 This is the case when you have for example 40GB available across all your region servers' block caches but you need to process 1TB of data.
767 One of the reasons is that the churn generated by the evictions will trigger more garbage collections unnecessarily.
768 Here are two use cases:
770 * Fully random reading pattern: This is a case where you almost never access the same row twice within a short amount of time such that the chance of hitting a cached block is close to 0.
771 Setting block caching on such a table is a waste of memory and CPU cycles, more so that it will generate more garbage to pick up by the JVM.
772 For more information on monitoring GC, see <<trouble.log.gc>>.
773 * Mapping a table: In a typical MapReduce job that takes a table in input, every row will be read only once so there's no need to put them into the block cache.
774 The Scan object has the option of turning this off via the setCaching method (set it to false). You can still keep block caching turned on on this table if you need fast random read access.
775 An example would be counting the number of rows in a table that serves live traffic, caching every block of that table would create massive churn and would surely evict data that's currently in use.
777 [[data.blocks.in.fscache]]
778 ===== Caching META blocks only (DATA blocks in fscache)
780 An interesting setup is one where we cache META blocks only and we read DATA blocks in on each access.
781 If the DATA blocks fit inside fscache, this alternative may make sense when access is completely random across a very large dataset.
782 To enable this setup, alter your table and for each column family set `BLOCKCACHE => 'false'`.
783 You are 'disabling' the BlockCache for this column family only. You can never disable the caching of META blocks.
784 Since link:https://issues.apache.org/jira/browse/HBASE-4683[HBASE-4683 Always cache index and bloom blocks], we will cache META blocks even if the BlockCache is disabled.
786 [[offheap.blockcache]]
787 ==== Off-heap Block Cache
789 [[enable.bucketcache]]
790 ===== How to Enable BucketCache
792 The usual deploy of BucketCache is via a managing class that sets up two caching tiers: an L1 on-heap cache implemented by LruBlockCache and a second L2 cache implemented with BucketCache.
793 The managing class is link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CombinedBlockCache.html[CombinedBlockCache] by default.
794 The previous link describes the caching 'policy' implemented by CombinedBlockCache.
795 In short, it works by keeping meta blocks -- INDEX and BLOOM in the L1, on-heap LruBlockCache tier -- and DATA blocks are kept in the L2, BucketCache tier.
796 It is possible to amend this behavior in HBase since version 1.0 and ask that a column family have both its meta and DATA blocks hosted on-heap in the L1 tier by setting `cacheDataInL1` via `(HColumnDescriptor.setCacheDataInL1(true)` or in the shell, creating or amending column families setting `CACHE_DATA_IN_L1` to true: e.g.
799 hbase(main):003:0> create 't', {NAME => 't', CONFIGURATION => {CACHE_DATA_IN_L1 => 'true'}}
802 The BucketCache Block Cache can be deployed on-heap, off-heap, or file based.
803 You set which via the `hbase.bucketcache.ioengine` setting.
804 Setting it to `heap` will have BucketCache deployed inside the allocated Java heap.
805 Setting it to `offheap` will have BucketCache make its allocations off-heap, and an ioengine setting of `file:PATH_TO_FILE` will direct BucketCache to use a file caching (Useful in particular if you have some fast I/O attached to the box such as SSDs).
807 It is possible to deploy an L1+L2 setup where we bypass the CombinedBlockCache policy and have BucketCache working as a strict L2 cache to the L1 LruBlockCache.
808 For such a setup, set `CacheConfig.BUCKET_CACHE_COMBINED_KEY` to `false`.
809 In this mode, on eviction from L1, blocks go to L2.
810 When a block is cached, it is cached first in L1.
811 When we go to look for a cached block, we look first in L1 and if none found, then search L2.
812 Let us call this deploy format, _Raw L1+L2_.
814 Other BucketCache configs include: specifying a location to persist cache to across restarts, how many threads to use writing the cache, etc.
815 See the link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html[CacheConfig.html] class for configuration options and descriptions.
819 ====== BucketCache Example Configuration
820 This sample provides a configuration for a 4 GB off-heap BucketCache with a 1 GB on-heap cache.
822 Configuration is performed on the RegionServer.
824 Setting `hbase.bucketcache.ioengine` and `hbase.bucketcache.size` > 0 enables `CombinedBlockCache`.
825 Let us presume that the RegionServer has been set to run with a 5G heap: i.e. `HBASE_HEAPSIZE=5g`.
828 . First, edit the RegionServer's _hbase-env.sh_ and set `HBASE_OFFHEAPSIZE` to a value greater than the off-heap size wanted, in this case, 4 GB (expressed as 4G). Let's set it to 5G.
829 That'll be 4G for our off-heap cache and 1G for any other uses of off-heap memory (there are other users of off-heap memory other than BlockCache; e.g.
830 DFSClient in RegionServer can make use of off-heap memory). See <<direct.memory>>.
837 . Next, add the following configuration to the RegionServer's _hbase-site.xml_.
842 <name>hbase.bucketcache.ioengine</name>
843 <value>offheap</value>
846 <name>hfile.block.cache.size</name>
850 <name>hbase.bucketcache.size</name>
855 . Restart or rolling restart your cluster, and check the logs for any issues.
858 In the above, we set the BucketCache to be 4G.
859 We configured the on-heap LruBlockCache have 20% (0.2) of the RegionServer's heap size (0.2 * 5G = 1G). In other words, you configure the L1 LruBlockCache as you would normally (as if there were no L2 cache present).
861 link:https://issues.apache.org/jira/browse/HBASE-10641[HBASE-10641] introduced the ability to configure multiple sizes for the buckets of the BucketCache, in HBase 0.98 and newer.
862 To configurable multiple bucket sizes, configure the new property `hfile.block.cache.sizes` (instead of `hfile.block.cache.size`) to a comma-separated list of block sizes, ordered from smallest to largest, with no spaces.
863 The goal is to optimize the bucket sizes based on your data access patterns.
864 The following example configures buckets of size 4096 and 8192.
869 <name>hfile.block.cache.sizes</name>
870 <value>4096,8192</value>
875 .Direct Memory Usage In HBase
878 The default maximum direct memory varies by JVM.
879 Traditionally it is 64M or some relation to allocated heap size (-Xmx) or no limit at all (JDK7 apparently). HBase servers use direct memory, in particular short-circuit reading, the hosted DFSClient will allocate direct memory buffers.
880 If you do off-heap block caching, you'll be making use of direct memory.
881 Starting your JVM, make sure the `-XX:MaxDirectMemorySize` setting in _conf/hbase-env.sh_ is set to some value that is higher than what you have allocated to your off-heap BlockCache (`hbase.bucketcache.size`). It should be larger than your off-heap block cache and then some for DFSClient usage (How much the DFSClient uses is not easy to quantify; it is the number of open HFiles * `hbase.dfs.client.read.shortcircuit.buffer.size` where `hbase.dfs.client.read.shortcircuit.buffer.size` is set to 128k in HBase -- see _hbase-default.xml_ default configurations). Direct memory, which is part of the Java process heap, is separate from the object heap allocated by -Xmx.
882 The value allocated by `MaxDirectMemorySize` must not exceed physical RAM, and is likely to be less than the total available RAM due to other memory requirements and system constraints.
884 You can see how much memory -- on-heap and off-heap/direct -- a RegionServer is configured to use and how much it is using at any one time by looking at the _Server Metrics: Memory_ tab in the UI.
885 It can also be gotten via JMX.
886 In particular the direct memory currently used by the server can be found on the `java.nio.type=BufferPool,name=direct` bean.
887 Terracotta has a link:http://terracotta.org/documentation/4.0/bigmemorygo/configuration/storage-options[good write up] on using off-heap memory in Java.
888 It is for their product BigMemory but a lot of the issues noted apply in general to any attempt at going off-heap. Check it out.
891 .hbase.bucketcache.percentage.in.combinedcache
894 This is a pre-HBase 1.0 configuration removed because it was confusing.
895 It was a float that you would set to some value between 0.0 and 1.0.
897 If the deploy was using CombinedBlockCache, then the LruBlockCache L1 size was calculated to be `(1 - hbase.bucketcache.percentage.in.combinedcache) * size-of-bucketcache` and the BucketCache size was `hbase.bucketcache.percentage.in.combinedcache * size-of-bucket-cache`.
898 where size-of-bucket-cache itself is EITHER the value of the configuration `hbase.bucketcache.size` IF it was specified as Megabytes OR `hbase.bucketcache.size` * `-XX:MaxDirectMemorySize` if `hbase.bucketcache.size` is between 0 and 1.0.
900 In 1.0, it should be more straight-forward.
901 L1 LruBlockCache size is set as a fraction of java heap using `hfile.block.cache.size setting` (not the best name) and L2 is set as above either in absolute Megabytes or as a fraction of allocated maximum direct memory.
904 ==== Compressed BlockCache
906 link:https://issues.apache.org/jira/browse/HBASE-11331[HBASE-11331] introduced lazy BlockCache decompression, more simply referred to as compressed BlockCache.
907 When compressed BlockCache is enabled data and encoded data blocks are cached in the BlockCache in their on-disk format, rather than being decompressed and decrypted before caching.
909 For a RegionServer hosting more data than can fit into cache, enabling this feature with SNAPPY compression has been shown to result in 50% increase in throughput and 30% improvement in mean latency while, increasing garbage collection by 80% and increasing overall CPU load by 2%. See HBASE-11331 for more details about how performance was measured and achieved.
910 For a RegionServer hosting data that can comfortably fit into cache, or if your workload is sensitive to extra CPU or garbage-collection load, you may receive less benefit.
912 The compressed BlockCache is disabled by default. To enable it, set `hbase.block.data.cachecompressed` to `true` in _hbase-site.xml_ on all RegionServers.
914 [[regionserver_splitting_implementation]]
915 === RegionServer Splitting Implementation
917 As write requests are handled by the region server, they accumulate in an in-memory storage system called the _memstore_. Once the memstore fills, its content are written to disk as additional store files. This event is called a _memstore flush_. As store files accumulate, the RegionServer will <<compaction,compact>> them into fewer, larger files. After each flush or compaction finishes, the amount of data stored in the region has changed. The RegionServer consults the region split policy to determine if the region has grown too large or should be split for another policy-specific reason. A region split request is enqueued if the policy recommends it.
919 Logically, the process of splitting a region is simple. We find a suitable point in the keyspace of the region where we should divide the region in half, then split the region's data into two new regions at that point. The details of the process however are not simple. When a split happens, the newly created _daughter regions_ do not rewrite all the data into new files immediately. Instead, they create small files similar to symbolic link files, named link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/Reference.html[Reference files], which point to either the top or bottom part of the parent store file according to the split point. The reference file is used just like a regular data file, but only half of the records are considered. The region can only be split if there are no more references to the immutable data files of the parent region. Those reference files are cleaned gradually by compactions, so that the region will stop referring to its parents files, and can be split further.
921 Although splitting the region is a local decision made by the RegionServer, the split process itself must coordinate with many actors. The RegionServer notifies the Master before and after the split, updates the `.META.` table so that clients can discover the new daughter regions, and rearranges the directory structure and data files in HDFS. Splitting is a multi-task process. To enable rollback in case of an error, the RegionServer keeps an in-memory journal about the execution state. The steps taken by the RegionServer to execute the split are illustrated in <<regionserver_split_process_image>>. Each step is labeled with its step number. Actions from RegionServers or Master are shown in red, while actions from the clients are show in green.
923 [[regionserver_split_process_image]]
924 .RegionServer Split Process
925 image::region_split_process.png[Region Split Process]
927 . The RegionServer decides locally to split the region, and prepares the split. *THE SPLIT TRANSACTION IS STARTED.* As a first step, the RegionServer acquires a shared read lock on the table to prevent schema modifications during the splitting process. Then it creates a znode in zookeeper under `/hbase/region-in-transition/region-name`, and sets the znode's state to `SPLITTING`.
928 . The Master learns about this znode, since it has a watcher for the parent `region-in-transition` znode.
929 . The RegionServer creates a sub-directory named `.splits` under the parent’s `region` directory in HDFS.
930 . The RegionServer closes the parent region and marks the region as offline in its local data structures. *THE SPLITTING REGION IS NOW OFFLINE.* At this point, client requests coming to the parent region will throw `NotServingRegionException`. The client will retry with some backoff. The closing region is flushed.
931 . The RegionServer creates region directories under the `.splits` directory, for daughter
932 regions A and B, and creates necessary data structures. Then it splits the store files,
933 in the sense that it creates two Reference files per store file in the parent region.
934 Those reference files will point to the parent region's files.
935 . The RegionServer creates the actual region directory in HDFS, and moves the reference files for each daughter.
936 . The RegionServer sends a `Put` request to the `.META.` table, to set the parent as offline in the `.META.` table and add information about daughter regions. At this point, there won’t be individual entries in `.META.` for the daughters. Clients will see that the parent region is split if they scan `.META.`, but won’t know about the daughters until they appear in `.META.`. Also, if this `Put` to `.META`. succeeds, the parent will be effectively split. If the RegionServer fails before this RPC succeeds, Master and the next Region Server opening the region will clean dirty state about the region split. After the `.META.` update, though, the region split will be rolled-forward by Master.
937 . The RegionServer opens daughters A and B in parallel.
938 . The RegionServer adds the daughters A and B to `.META.`, together with information that it hosts the regions. *THE SPLIT REGIONS (DAUGHTERS WITH REFERENCES TO PARENT) ARE NOW ONLINE.* After this point, clients can discover the new regions and issue requests to them. Clients cache the `.META.` entries locally, but when they make requests to the RegionServer or `.META.`, their caches will be invalidated, and they will learn about the new regions from `.META.`.
939 . The RegionServer updates znode `/hbase/region-in-transition/region-name` in ZooKeeper to state `SPLIT`, so that the master can learn about it. The balancer can freely re-assign the daughter regions to other region servers if necessary. *THE SPLIT TRANSACTION IS NOW FINISHED.*
940 . After the split, `.META.` and HDFS will still contain references to the parent region. Those references will be removed when compactions in daughter regions rewrite the data files. Garbage collection tasks in the master periodically check whether the daughter regions still refer to the parent region's files. If not, the parent region will be removed.
943 === Write Ahead Log (WAL)
948 The _Write Ahead Log (WAL)_ records all changes to data in HBase, to file-based storage.
949 Under normal operations, the WAL is not needed because data changes move from the MemStore to StoreFiles.
950 However, if a RegionServer crashes or becomes unavailable before the MemStore is flushed, the WAL ensures that the changes to the data can be replayed.
951 If writing to the WAL fails, the entire operation to modify the data fails.
953 HBase uses an implementation of the link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/wal/WAL.html[WAL] interface.
954 Usually, there is only one instance of a WAL per RegionServer. An exception
955 is the RegionServer that is carrying _hbase:meta_; the _meta_ table gets its
957 The RegionServer records Puts and Deletes to its WAL, before recording them
958 these Mutations <<store.memstore>> for the affected <<store>>.
963 Prior to 2.0, the interface for WALs in HBase was named `HLog`.
964 In 0.94, HLog was the name of the implementation of the WAL.
965 You will likely find references to the HLog in documentation tailored to these older versions.
968 The WAL resides in HDFS in the _/hbase/WALs/_ directory, with subdirectories per region.
970 For more general information about the concept of write ahead logs, see the Wikipedia
971 link:http://en.wikipedia.org/wiki/Write-ahead_logging[Write-Ahead Log] article.
976 In HBase, there are a number of WAL imlementations (or 'Providers'). Each is known
977 by a short name label (that unfortunately is not always descriptive). You set the provider in
978 _hbase-site.xml_ passing the WAL provder short-name as the value on the
979 _hbase.wal.provider_ property (Set the provider for _hbase:meta_ using the
980 _hbase.wal.meta_provider_ property).
982 * _asyncfs_: The *default*. New since hbase-2.0.0 (HBASE-15536, HBASE-14790). This _AsyncFSWAL_ provider, as it identifies itself in RegionServer logs, is built on a new non-blocking dfsclient implementation. It is currently resident in the hbase codebase but intent is to move it back up into HDFS itself. WALs edits are written concurrently ("fan-out") style to each of the WAL-block replicas on each DataNode rather than in a chained pipeline as the default client does. Latencies should be better. See link:https://www.slideshare.net/HBaseCon/apache-hbase-improvements-and-practices-at-xiaomi[Apache HBase Improements and Practices at Xiaomi] at slide 14 onward for more detail on implementation.
983 * _filesystem_: This was the default in hbase-1.x releases. It is built on the blocking _DFSClient_ and writes to replicas in classic _DFSCLient_ pipeline mode. In logs it identifies as _FSHLog_ or _FSHLogProvider_.
984 * _multiwal_: This provider is made of multiple instances of _asyncfs_ or _filesystem_. See the next section for more on _multiwal_.
986 Look for the lines like the below in the RegionServer log to see which provider is in place (The below shows the default AsyncFSWALProvider):
989 2018-04-02 13:22:37,983 INFO [regionserver/ve0528:16020] wal.WALFactory: Instantiating WALProvider of type class org.apache.hadoop.hbase.wal.AsyncFSWALProvider
994 With a single WAL per RegionServer, the RegionServer must write to the WAL serially, because HDFS files must be sequential. This causes the WAL to be a performance bottleneck.
996 HBase 1.0 introduces support MultiWal in link:https://issues.apache.org/jira/browse/HBASE-5699[HBASE-5699]. MultiWAL allows a RegionServer to write multiple WAL streams in parallel, by using multiple pipelines in the underlying HDFS instance, which increases total throughput during writes. This parallelization is done by partitioning incoming edits by their Region. Thus, the current implementation will not help with increasing the throughput to a single Region.
998 RegionServers using the original WAL implementation and those using the MultiWAL implementation can each handle recovery of either set of WALs, so a zero-downtime configuration update is possible through a rolling restart.
1001 To configure MultiWAL for a RegionServer, set the value of the property `hbase.wal.provider` to `multiwal` by pasting in the following XML:
1006 <name>hbase.wal.provider</name>
1007 <value>multiwal</value>
1011 Restart the RegionServer for the changes to take effect.
1013 To disable MultiWAL for a RegionServer, unset the property and restart the RegionServer.
1023 A RegionServer serves many regions.
1024 All of the regions in a region server share the same active WAL file.
1025 Each edit in the WAL file includes information about which region it belongs to.
1026 When a region is opened, the edits in the WAL file which belong to that region need to be replayed.
1027 Therefore, edits in the WAL file must be grouped by region so that particular sets can be replayed to regenerate the data in a particular region.
1028 The process of grouping the WAL edits by region is called _log splitting_.
1029 It is a critical process for recovering data if a region server fails.
1031 Log splitting is done by the HMaster during cluster start-up or by the ServerShutdownHandler as a region server shuts down.
1032 So that consistency is guaranteed, affected regions are unavailable until data is restored.
1033 All WAL edits need to be recovered and replayed before a given region can become available again.
1034 As a result, regions affected by log splitting are unavailable until the process completes.
1036 .Procedure: Log Splitting, Step by Step
1037 . The _/hbase/WALs/<host>,<port>,<startcode>_ directory is renamed.
1039 Renaming the directory is important because a RegionServer may still be up and accepting requests even if the HMaster thinks it is down.
1040 If the RegionServer does not respond immediately and does not heartbeat its ZooKeeper session, the HMaster may interpret this as a RegionServer failure.
1041 Renaming the logs directory ensures that existing, valid WAL files which are still in use by an active but busy RegionServer are not written to by accident.
1043 The new directory is named according to the following pattern:
1046 /hbase/WALs/<host>,<port>,<startcode>-splitting
1049 An example of such a renamed directory might look like the following:
1052 /hbase/WALs/srv.example.com,60020,1254173957298-splitting
1055 . Each log file is split, one at a time.
1057 The log splitter reads the log file one edit entry at a time and puts each edit entry into the buffer corresponding to the edit's region.
1058 At the same time, the splitter starts several writer threads.
1059 Writer threads pick up a corresponding buffer and write the edit entries in the buffer to a temporary recovered edit file.
1060 The temporary edit file is stored to disk with the following naming pattern:
1063 /hbase/<table_name>/<region_id>/recovered.edits/.temp
1066 This file is used to store all the edits in the WAL log for this region.
1067 After log splitting completes, the _.temp_ file is renamed to the sequence ID of the first log written to the file.
1069 To determine whether all edits have been written, the sequence ID is compared to the sequence of the last edit that was written to the HFile.
1070 If the sequence of the last edit is greater than or equal to the sequence ID included in the file name, it is clear that all writes from the edit file have been completed.
1072 . After log splitting is complete, each affected region is assigned to a RegionServer.
1074 When the region is opened, the _recovered.edits_ folder is checked for recovered edits files.
1075 If any such files are present, they are replayed by reading the edits and saving them to the MemStore.
1076 After all edit files are replayed, the contents of the MemStore are written to disk (HFile) and the edit files are deleted.
1079 ===== Handling of Errors During Log Splitting
1081 If you set the `hbase.hlog.split.skip.errors` option to `true`, errors are treated as follows:
1083 * Any error encountered during splitting will be logged.
1084 * The problematic WAL log will be moved into the _.corrupt_ directory under the hbase `rootdir`,
1085 * Processing of the WAL will continue
1087 If the `hbase.hlog.split.skip.errors` option is set to `false`, the default, the exception will be propagated and the split will be logged as failed.
1088 See link:https://issues.apache.org/jira/browse/HBASE-2958[HBASE-2958 When
1089 hbase.hlog.split.skip.errors is set to false, we fail the split but that's it].
1090 We need to do more than just fail split if this flag is set.
1092 ====== How EOFExceptions are treated when splitting a crashed RegionServer's WALs
1094 If an EOFException occurs while splitting logs, the split proceeds even when `hbase.hlog.split.skip.errors` is set to `false`.
1095 An EOFException while reading the last log in the set of files to split is likely, because the RegionServer was likely in the process of writing a record at the time of a crash.
1096 For background, see link:https://issues.apache.org/jira/browse/HBASE-2643[HBASE-2643 Figure how to deal with eof splitting logs]
1098 ===== Performance Improvements during Log Splitting
1100 WAL log splitting and recovery can be resource intensive and take a long time, depending on the number of RegionServers involved in the crash and the size of the regions. <<distributed.log.splitting>> was developed to improve performance during log splitting.
1102 [[distributed.log.splitting]]
1103 .Enabling or Disabling Distributed Log Splitting
1105 Distributed log processing is enabled by default since HBase 0.92.
1106 The setting is controlled by the `hbase.master.distributed.log.splitting` property, which can be set to `true` or `false`, but defaults to `true`.
1108 [[log.splitting.step.by.step]]
1109 .Distributed Log Splitting, Step by Step
1111 After configuring distributed log splitting, the HMaster controls the process.
1112 The HMaster enrolls each RegionServer in the log splitting process, and the actual work of splitting the logs is done by the RegionServers.
1113 The general process for log splitting, as described in <<log.splitting.step.by.step>> still applies here.
1115 . If distributed log processing is enabled, the HMaster creates a _split log manager_ instance when the cluster is started.
1116 .. The split log manager manages all log files which need to be scanned and split.
1117 .. The split log manager places all the logs into the ZooKeeper splitWAL node (_/hbase/splitWAL_) as tasks.
1118 .. You can view the contents of the splitWAL by issuing the following `zkCli` command. Example output is shown.
1123 [hdfs%3A%2F%2Fhost2.sample.com%3A56020%2Fhbase%2FWALs%2Fhost8.sample.com%2C57020%2C1340474893275-splitting%2Fhost8.sample.com%253A57020.1340474893900,
1124 hdfs%3A%2F%2Fhost2.sample.com%3A56020%2Fhbase%2FWALs%2Fhost3.sample.com%2C57020%2C1340474893299-splitting%2Fhost3.sample.com%253A57020.1340474893931,
1125 hdfs%3A%2F%2Fhost2.sample.com%3A56020%2Fhbase%2FWALs%2Fhost4.sample.com%2C57020%2C1340474893287-splitting%2Fhost4.sample.com%253A57020.1340474893946]
1128 The output contains some non-ASCII characters.
1129 When decoded, it looks much more simple:
1132 [hdfs://host2.sample.com:56020/hbase/WALs
1133 /host8.sample.com,57020,1340474893275-splitting
1134 /host8.sample.com%3A57020.1340474893900,
1135 hdfs://host2.sample.com:56020/hbase/WALs
1136 /host3.sample.com,57020,1340474893299-splitting
1137 /host3.sample.com%3A57020.1340474893931,
1138 hdfs://host2.sample.com:56020/hbase/WALs
1139 /host4.sample.com,57020,1340474893287-splitting
1140 /host4.sample.com%3A57020.1340474893946]
1143 The listing represents WAL file names to be scanned and split, which is a list of log splitting tasks.
1145 . The split log manager monitors the log-splitting tasks and workers.
1147 The split log manager is responsible for the following ongoing tasks:
1149 * Once the split log manager publishes all the tasks to the splitWAL znode, it monitors these task nodes and waits for them to be processed.
1150 * Checks to see if there are any dead split log workers queued up.
1151 If it finds tasks claimed by unresponsive workers, it will resubmit those tasks.
1152 If the resubmit fails due to some ZooKeeper exception, the dead worker is queued up again for retry.
1153 * Checks to see if there are any unassigned tasks.
1154 If it finds any, it create an ephemeral rescan node so that each split log worker is notified to re-scan unassigned tasks via the `nodeChildrenChanged` ZooKeeper event.
1155 * Checks for tasks which are assigned but expired.
1156 If any are found, they are moved back to `TASK_UNASSIGNED` state again so that they can be retried.
1157 It is possible that these tasks are assigned to slow workers, or they may already be finished.
1158 This is not a problem, because log splitting tasks have the property of idempotence.
1159 In other words, the same log splitting task can be processed many times without causing any problem.
1160 * The split log manager watches the HBase split log znodes constantly.
1161 If any split log task node data is changed, the split log manager retrieves the node data.
1162 The node data contains the current state of the task.
1163 You can use the `zkCli` `get` command to retrieve the current state of a task.
1164 In the example output below, the first line of the output shows that the task is currently unassigned.
1167 get /hbase/splitWAL/hdfs%3A%2F%2Fhost2.sample.com%3A56020%2Fhbase%2FWALs%2Fhost6.sample.com%2C57020%2C1340474893287-splitting%2Fhost6.sample.com%253A57020.1340474893945
1169 unassigned host2.sample.com:57000
1171 ctime = Sat Jun 23 11:13:40 PDT 2012
1175 Based on the state of the task whose data is changed, the split log manager does one of the following:
1177 * Resubmit the task if it is unassigned
1178 * Heartbeat the task if it is assigned
1179 * Resubmit or fail the task if it is resigned (see <<distributed.log.replay.failure.reasons>>)
1180 * Resubmit or fail the task if it is completed with errors (see <<distributed.log.replay.failure.reasons>>)
1181 * Resubmit or fail the task if it could not complete due to errors (see <<distributed.log.replay.failure.reasons>>)
1182 * Delete the task if it is successfully completed or failed
1184 [[distributed.log.replay.failure.reasons]]
1186 .Reasons a Task Will Fail
1188 * The task has been deleted.
1189 * The node no longer exists.
1190 * The log status manager failed to move the state of the task to `TASK_UNASSIGNED`.
1191 * The number of resubmits is over the resubmit threshold.
1194 . Each RegionServer's split log worker performs the log-splitting tasks.
1196 Each RegionServer runs a daemon thread called the _split log worker_, which does the work to split the logs.
1197 The daemon thread starts when the RegionServer starts, and registers itself to watch HBase znodes.
1198 If any splitWAL znode children change, it notifies a sleeping worker thread to wake up and grab more tasks.
1199 If a worker's current task's node data is changed,
1200 the worker checks to see if the task has been taken by another worker.
1201 If so, the worker thread stops work on the current task.
1203 The worker monitors the splitWAL znode constantly.
1204 When a new task appears, the split log worker retrieves the task paths and checks each one until it finds an unclaimed task, which it attempts to claim.
1205 If the claim was successful, it attempts to perform the task and updates the task's `state` property based on the splitting outcome.
1206 At this point, the split log worker scans for another unclaimed task.
1208 .How the Split Log Worker Approaches a Task
1209 * It queries the task state and only takes action if the task is in `TASK_UNASSIGNED `state.
1210 * If the task is in `TASK_UNASSIGNED` state, the worker attempts to set the state to `TASK_OWNED` by itself.
1211 If it fails to set the state, another worker will try to grab it.
1212 The split log manager will also ask all workers to rescan later if the task remains unassigned.
1213 * If the worker succeeds in taking ownership of the task, it tries to get the task state again to make sure it really gets it asynchronously.
1214 In the meantime, it starts a split task executor to do the actual work:
1215 ** Get the HBase root folder, create a temp folder under the root, and split the log file to the temp folder.
1216 ** If the split was successful, the task executor sets the task to state `TASK_DONE`.
1217 ** If the worker catches an unexpected IOException, the task is set to state `TASK_ERR`.
1218 ** If the worker is shutting down, set the task to state `TASK_RESIGNED`.
1219 ** If the task is taken by another worker, just log it.
1222 . The split log manager monitors for uncompleted tasks.
1224 The split log manager returns when all tasks are completed successfully.
1225 If all tasks are completed with some failures, the split log manager throws an exception so that the log splitting can be retried.
1226 Due to an asynchronous implementation, in very rare cases, the split log manager loses track of some completed tasks.
1227 For that reason, it periodically checks for remaining uncompleted task in its task map or ZooKeeper.
1228 If none are found, it throws an exception so that the log splitting can be retried right away instead of hanging there waiting for something that won't happen.
1231 ==== WAL Compression ====
1233 The content of the WAL can be compressed using LRU Dictionary compression.
1234 This can be used to speed up WAL replication to different datanodes.
1235 The dictionary can store up to 2^15^ elements; eviction starts after this number is exceeded.
1237 To enable WAL compression, set the `hbase.regionserver.wal.enablecompression` property to `true`.
1238 The default value for this property is `false`.
1239 By default, WAL tag compression is turned on when WAL compression is enabled.
1240 You can turn off WAL tag compression by setting the `hbase.regionserver.wal.tags.enablecompression` property to 'false'.
1242 A possible downside to WAL compression is that we lose more data from the last block in the WAL if it ill-terminated
1243 mid-write. If entries in this last block were added with new dictionary entries but we failed persist the amended
1244 dictionary because of an abrupt termination, a read of this last block may not be able to resolve last-written entries.
1248 It is possible to set _durability_ on each Mutation or on a Table basis. Options include:
1250 * _SKIP_WAL_: Do not write Mutations to the WAL (See the next section, <<wal.disable>>).
1251 * _ASYNC_WAL_: Write the WAL asynchronously; do not hold-up clients waiting on the sync of their write to the filesystem but return immediately. The edit becomes visible. Meanwhile, in the background, the Mutation will be flushed to the WAL at some time later. This option currently may lose data. See HBASE-16689.
1252 * _SYNC_WAL_: The *default*. Each edit is sync'd to HDFS before we return success to the client.
1253 * _FSYNC_WAL_: Each edit is fsync'd to HDFS and the filesystem before we return success to the client.
1255 Do not confuse the _ASYNC_WAL_ option on a Mutation or Table with the _AsyncFSWAL_ writer; they are distinct
1256 options unfortunately closely named
1259 ==== Disabling the WAL
1261 It is possible to disable the WAL, to improve performance in certain specific situations.
1262 However, disabling the WAL puts your data at risk.
1263 The only situation where this is recommended is during a bulk load.
1264 This is because, in the event of a problem, the bulk load can be re-run with no risk of data loss.
1266 The WAL is disabled by calling the HBase client field `Mutation.writeToWAL(false)`.
1267 Use the `Mutation.setDurability(Durability.SKIP_WAL)` and Mutation.getDurability() methods to set and get the field's value.
1268 There is no way to disable the WAL for only a specific table.
1270 WARNING: If you disable the WAL for anything other than bulk loads, your data is at risk.
1276 Regions are the basic element of availability and distribution for tables, and are comprised of a Store per Column Family.
1277 The hierarchy of objects is as follows:
1281 Region (Regions for the table)
1282 Store (Store per ColumnFamily for each Region for the table)
1283 MemStore (MemStore for each Store for each Region for the table)
1284 StoreFile (StoreFiles for each Store for each Region for the table)
1285 Block (Blocks within a StoreFile within a Store for each Region for the table)
1288 For a description of what HBase files look like when written to HDFS, see <<trouble.namenode.hbase.objects>>.
1290 [[arch.regions.size]]
1291 === Considerations for Number of Regions
1293 In general, HBase is designed to run with a small (20-200) number of relatively large (5-20Gb) regions per server.
1294 The considerations for this are as follows:
1296 [[too_many_regions]]
1297 ==== Why should I keep my Region count low?
1299 Typically you want to keep your region count low on HBase for numerous reasons.
1300 Usually right around 100 regions per RegionServer has yielded the best results.
1301 Here are some of the reasons below for keeping region count low:
1303 . MSLAB (MemStore-local allocation buffer) requires 2MB per MemStore (that's 2MB per family per region). 1000 regions that have 2 families each is 3.9GB of heap used, and it's not even storing data yet.
1304 NB: the 2MB value is configurable.
1305 . If you fill all the regions at somewhat the same rate, the global memory usage makes it that it forces tiny flushes when you have too many regions which in turn generates compactions.
1306 Rewriting the same data tens of times is the last thing you want.
1307 An example is filling 1000 regions (with one family) equally and let's consider a lower bound for global MemStore usage of 5GB (the region server would have a big heap). Once it reaches 5GB it will force flush the biggest region, at that point they should almost all have about 5MB of data so it would flush that amount.
1308 5MB inserted later, it would flush another region that will now have a bit over 5MB of data, and so on.
1309 This is currently the main limiting factor for the number of regions; see <<ops.capacity.regions.count>> for detailed formula.
1310 . The master as is is allergic to tons of regions, and will take a lot of time assigning them and moving them around in batches.
1311 The reason is that it's heavy on ZK usage, and it's not very async at the moment (could really be improved -- and has been improved a bunch in 0.96 HBase).
1312 . In older versions of HBase (pre-HFile v2, 0.90 and previous), tons of regions on a few RS can cause the store file index to rise, increasing heap usage and potentially creating memory pressure or OOME on the RSs
1314 Another issue is the effect of the number of regions on MapReduce jobs; it is typical to have one mapper per HBase region.
1315 Thus, hosting only 5 regions per RS may not be enough to get sufficient number of tasks for a MapReduce job, while 1000 regions will generate far too many tasks.
1317 See <<ops.capacity.regions>> for configuration guidelines.
1319 [[regions.arch.assignment]]
1320 === Region-RegionServer Assignment
1322 This section describes how Regions are assigned to RegionServers.
1324 [[regions.arch.assignment.startup]]
1327 When HBase starts regions are assigned as follows (short version):
1329 . The Master invokes the `AssignmentManager` upon startup.
1330 . The `AssignmentManager` looks at the existing region assignments in `hbase:meta`.
1331 . If the region assignment is still valid (i.e., if the RegionServer is still online) then the assignment is kept.
1332 . If the assignment is invalid, then the `LoadBalancerFactory` is invoked to assign the region.
1333 The load balancer (`StochasticLoadBalancer` by default in HBase 1.0) assign the region to a RegionServer.
1334 . `hbase:meta` is updated with the RegionServer assignment (if needed) and the RegionServer start codes (start time of the RegionServer process) upon region opening by the RegionServer.
1336 [[regions.arch.assignment.failover]]
1339 When a RegionServer fails:
1341 . The regions immediately become unavailable because the RegionServer is down.
1342 . The Master will detect that the RegionServer has failed.
1343 . The region assignments will be considered invalid and will be re-assigned just like the startup sequence.
1344 . In-flight queries are re-tried, and not lost.
1345 . Operations are switched to a new RegionServer within the following amount of time:
1349 ZooKeeper session timeout + split time + assignment/replay time
1353 [[regions.arch.balancer]]
1354 ==== Region Load Balancing
1356 Regions can be periodically moved by the <<master.processes.loadbalancer>>.
1358 [[regions.arch.states]]
1359 ==== Region State Transition
1361 HBase maintains a state for each region and persists the state in `hbase:meta`.
1362 The state of the `hbase:meta` region itself is persisted in ZooKeeper.
1363 You can see the states of regions in transition in the Master web UI.
1364 Following is the list of possible region states.
1366 .Possible Region States
1367 * `OFFLINE`: the region is offline and not opening
1368 * `OPENING`: the region is in the process of being opened
1369 * `OPEN`: the region is open and the RegionServer has notified the master
1370 * `FAILED_OPEN`: the RegionServer failed to open the region
1371 * `CLOSING`: the region is in the process of being closed
1372 * `CLOSED`: the RegionServer has closed the region and notified the master
1373 * `FAILED_CLOSE`: the RegionServer failed to close the region
1374 * `SPLITTING`: the RegionServer notified the master that the region is splitting
1375 * `SPLIT`: the RegionServer notified the master that the region has finished splitting
1376 * `SPLITTING_NEW`: this region is being created by a split which is in progress
1377 * `MERGING`: the RegionServer notified the master that this region is being merged with another region
1378 * `MERGED`: the RegionServer notified the master that this region has been merged
1379 * `MERGING_NEW`: this region is being created by a merge of two regions
1381 .Region State Transitions
1382 image::region_states.png[]
1385 * Brown: Offline state, a special state that can be transient (after closed before opening), terminal (regions of disabled tables), or initial (regions of newly created tables)
1386 * Palegreen: Online state that regions can serve requests
1387 * Lightblue: Transient states
1388 * Red: Failure states that need OPS attention
1389 * Gold: Terminal states of regions split/merged
1390 * Grey: Initial states of regions created through split/merge
1392 .Transition State Descriptions
1393 . The master moves a region from `OFFLINE` to `OPENING` state and tries to assign the region to a RegionServer.
1394 The RegionServer may or may not have received the open region request.
1395 The master retries sending the open region request to the RegionServer until the RPC goes through or the master runs out of retries.
1396 After the RegionServer receives the open region request, the RegionServer begins opening the region.
1397 . If the master is running out of retries, the master prevents the RegionServer from opening the region by moving the region to `CLOSING` state and trying to close it, even if the RegionServer is starting to open the region.
1398 . After the RegionServer opens the region, it continues to try to notify the master until the master moves the region to `OPEN` state and notifies the RegionServer.
1399 The region is now open.
1400 . If the RegionServer cannot open the region, it notifies the master.
1401 The master moves the region to `CLOSED` state and tries to open the region on a different RegionServer.
1402 . If the master cannot open the region on any of a certain number of regions, it moves the region to `FAILED_OPEN` state, and takes no further action until an operator intervenes from the HBase shell, or the server is dead.
1403 . The master moves a region from `OPEN` to `CLOSING` state.
1404 The RegionServer holding the region may or may not have received the close region request.
1405 The master retries sending the close request to the server until the RPC goes through or the master runs out of retries.
1406 . If the RegionServer is not online, or throws `NotServingRegionException`, the master moves the region to `OFFLINE` state and re-assigns it to a different RegionServer.
1407 . If the RegionServer is online, but not reachable after the master runs out of retries, the master moves the region to `FAILED_CLOSE` state and takes no further action until an operator intervenes from the HBase shell, or the server is dead.
1408 . If the RegionServer gets the close region request, it closes the region and notifies the master.
1409 The master moves the region to `CLOSED` state and re-assigns it to a different RegionServer.
1410 . Before assigning a region, the master moves the region to `OFFLINE` state automatically if it is in `CLOSED` state.
1411 . When a RegionServer is about to split a region, it notifies the master.
1412 The master moves the region to be split from `OPEN` to `SPLITTING` state and add the two new regions to be created to the RegionServer.
1413 These two regions are in `SPLITTING_NEW` state initially.
1414 . After notifying the master, the RegionServer starts to split the region.
1415 Once past the point of no return, the RegionServer notifies the master again so the master can update the `hbase:meta` table.
1416 However, the master does not update the region states until it is notified by the server that the split is done.
1417 If the split is successful, the splitting region is moved from `SPLITTING` to `SPLIT` state and the two new regions are moved from `SPLITTING_NEW` to `OPEN` state.
1418 . If the split fails, the splitting region is moved from `SPLITTING` back to `OPEN` state, and the two new regions which were created are moved from `SPLITTING_NEW` to `OFFLINE` state.
1419 . When a RegionServer is about to merge two regions, it notifies the master first.
1420 The master moves the two regions to be merged from `OPEN` to `MERGING` state, and adds the new region which will hold the contents of the merged regions region to the RegionServer.
1421 The new region is in `MERGING_NEW` state initially.
1422 . After notifying the master, the RegionServer starts to merge the two regions.
1423 Once past the point of no return, the RegionServer notifies the master again so the master can update the META.
1424 However, the master does not update the region states until it is notified by the RegionServer that the merge has completed.
1425 If the merge is successful, the two merging regions are moved from `MERGING` to `MERGED` state and the new region is moved from `MERGING_NEW` to `OPEN` state.
1426 . If the merge fails, the two merging regions are moved from `MERGING` back to `OPEN` state, and the new region which was created to hold the contents of the merged regions is moved from `MERGING_NEW` to `OFFLINE` state.
1427 . For regions in `FAILED_OPEN` or `FAILED_CLOSE` states, the master tries to close them again when they are reassigned by an operator via HBase Shell.
1429 [[regions.arch.locality]]
1430 === Region-RegionServer Locality
1432 Over time, Region-RegionServer locality is achieved via HDFS block replication.
1433 The HDFS client does the following by default when choosing locations to write replicas:
1435 . First replica is written to local node
1436 . Second replica is written to a random node on another rack
1437 . Third replica is written on the same rack as the second, but on a different node chosen randomly
1438 . Subsequent replicas are written on random nodes on the cluster.
1439 See _Replica Placement: The First Baby Steps_ on this page: link:https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html[HDFS Architecture]
1441 Thus, HBase eventually achieves locality for a region after a flush or a compaction.
1442 In a RegionServer failover situation a RegionServer may be assigned regions with non-local StoreFiles (because none of the replicas are local), however as new data is written in the region, or the table is compacted and StoreFiles are re-written, they will become "local" to the RegionServer.
1444 For more information, see _Replica Placement: The First Baby Steps_ on this page: link:https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html[HDFS Architecture] and also Lars George's blog on link:http://www.larsgeorge.com/2010/05/hbase-file-locality-in-hdfs.html[HBase and HDFS locality].
1446 [[arch.region.splits]]
1449 Regions split when they reach a configured threshold.
1450 Below we treat the topic in short.
1451 For a longer exposition, see link:http://hortonworks.com/blog/apache-hbase-region-splitting-and-merging/[Apache HBase Region Splitting and Merging] by our Enis Soztutar.
1453 Splits run unaided on the RegionServer; i.e. the Master does not participate.
1454 The RegionServer splits a region, offlines the split region and then adds the daughter regions to `hbase:meta`, opens daughters on the parent's hosting RegionServer and then reports the split to the Master.
1455 See <<disable.splitting>> for how to manually manage splits (and for why you might do this).
1457 ==== Custom Split Policies
1458 You can override the default split policy using a custom
1459 link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/regionserver/RegionSplitPolicy.html[RegionSplitPolicy](HBase 0.94+).
1460 Typically a custom split policy should extend HBase's default split policy:
1461 link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/regionserver/IncreasingToUpperBoundRegionSplitPolicy.html[IncreasingToUpperBoundRegionSplitPolicy].
1463 The policy can set globally through the HBase configuration or on a per-table
1466 .Configuring the Split Policy Globally in _hbase-site.xml_
1470 <name>hbase.regionserver.region.split.policy</name>
1471 <value>org.apache.hadoop.hbase.regionserver.IncreasingToUpperBoundRegionSplitPolicy</value>
1475 .Configuring a Split Policy On a Table Using the Java API
1477 HTableDescriptor tableDesc = new HTableDescriptor("test");
1478 tableDesc.setValue(HTableDescriptor.SPLIT_POLICY, ConstantSizeRegionSplitPolicy.class.getName());
1479 tableDesc.addFamily(new HColumnDescriptor(Bytes.toBytes("cf1")));
1480 admin.createTable(tableDesc);
1484 .Configuring the Split Policy On a Table Using HBase Shell
1486 hbase> create 'test', {METADATA => {'SPLIT_POLICY' => 'org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy'}},{NAME => 'cf1'}
1489 The policy can be set globally through the HBaseConfiguration used or on a per table basis:
1492 HTableDescriptor myHtd = ...;
1493 myHtd.setValue(HTableDescriptor.SPLIT_POLICY, MyCustomSplitPolicy.class.getName());
1496 NOTE: The `DisabledRegionSplitPolicy` policy blocks manual region splitting.
1498 [[manual_region_splitting_decisions]]
1499 === Manual Region Splitting
1501 It is possible to manually split your table, either at table creation (pre-splitting), or at a later time as an administrative action.
1502 You might choose to split your region for one or more of the following reasons.
1503 There may be other valid reasons, but the need to manually split your table might also point to problems with your schema design.
1505 .Reasons to Manually Split Your Table
1506 * Your data is sorted by timeseries or another similar algorithm that sorts new data at the end of the table.
1507 This means that the Region Server holding the last region is always under load, and the other Region Servers are idle, or mostly idle.
1508 See also <<timeseries>>.
1509 * You have developed an unexpected hotspot in one region of your table.
1510 For instance, an application which tracks web searches might be inundated by a lot of searches for a celebrity in the event of news about that celebrity.
1511 See <<perf.one.region,perf.one.region>> for more discussion about this particular scenario.
1512 * After a big increase in the number of RegionServers in your cluster, to get the load spread out quickly.
1513 * Before a bulk-load which is likely to cause unusual and uneven load across regions.
1515 See <<disable.splitting>> for a discussion about the dangers and possible benefits of managing splitting completely manually.
1517 NOTE: The `DisabledRegionSplitPolicy` policy blocks manual region splitting.
1519 ==== Determining Split Points
1521 The goal of splitting your table manually is to improve the chances of balancing the load across the cluster in situations where good rowkey design alone won't get you there.
1522 Keeping that in mind, the way you split your regions is very dependent upon the characteristics of your data.
1523 It may be that you already know the best way to split your table.
1524 If not, the way you split your table depends on what your keys are like.
1526 Alphanumeric Rowkeys::
1527 If your rowkeys start with a letter or number, you can split your table at letter or number boundaries.
1528 For instance, the following command creates a table with regions that split at each vowel, so the first region has A-D, the second region has E-H, the third region has I-N, the fourth region has O-V, and the fifth region has U-Z.
1530 Using a Custom Algorithm::
1531 The RegionSplitter tool is provided with HBase, and uses a _SplitAlgorithm_ to determine split points for you.
1532 As parameters, you give it the algorithm, desired number of regions, and column families.
1533 It includes three split algorithms.
1535 `link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/util/RegionSplitter.HexStringSplit.html[HexStringSplit]`
1536 algorithm, which assumes the row keys are hexadecimal strings.
1538 `link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/util/RegionSplitter.DecimalStringSplit.html[DecimalStringSplit]`
1539 algorithm, which assumes the row keys are decimal strings in the range 00000000 to 99999999.
1541 `link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/util/RegionSplitter.UniformSplit.html[UniformSplit]`,
1542 assumes the row keys are random byte arrays.
1543 You will probably need to develop your own
1544 `link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/util/RegionSplitter.SplitAlgorithm.html[SplitAlgorithm]`,
1545 using the provided ones as models.
1547 === Online Region Merges
1549 Both Master and RegionServer participate in the event of online region merges.
1550 Client sends merge RPC to the master, then the master moves the regions together to the RegionServer where the more heavily loaded region resided. Finally the master sends the merge request to this RegionServer which then runs the merge.
1551 Similar to process of region splitting, region merges run as a local transaction on the RegionServer. It offlines the regions and then merges two regions on the file system, atomically delete merging regions from `hbase:meta` and adds the merged region to `hbase:meta`, opens the merged region on the RegionServer and reports the merge to the Master.
1553 An example of region merges in the HBase shell
1556 $ hbase> merge_region 'ENCODED_REGIONNAME', 'ENCODED_REGIONNAME'
1557 $ hbase> merge_region 'ENCODED_REGIONNAME', 'ENCODED_REGIONNAME', true
1559 It's an asynchronous operation and call returns immediately without waiting merge completed.
1560 Passing `true` as the optional third parameter will force a merge. Normally only adjacent regions can be merged.
1561 The `force` parameter overrides this behaviour and is for expert use only.
1566 A Store hosts a MemStore and 0 or more StoreFiles (HFiles). A Store corresponds to a column family for a table for a given region.
1571 The MemStore holds in-memory modifications to the Store.
1572 Modifications are Cells/KeyValues.
1573 When a flush is requested, the current MemStore is moved to a snapshot and is cleared.
1574 HBase continues to serve edits from the new MemStore and backing snapshot until the flusher reports that the flush succeeded.
1575 At this point, the snapshot is discarded.
1576 Note that when the flush happens, MemStores that belong to the same region will all be flushed.
1580 A MemStore flush can be triggered under any of the conditions listed below.
1581 The minimum flush unit is per region, not at individual MemStore level.
1583 . When a MemStore reaches the size specified by `hbase.hregion.memstore.flush.size`,
1584 all MemStores that belong to its region will be flushed out to disk.
1586 . When the overall MemStore usage reaches the value specified by
1587 `hbase.regionserver.global.memstore.upperLimit`, MemStores from various regions
1588 will be flushed out to disk to reduce overall MemStore usage in a RegionServer.
1590 The flush order is based on the descending order of a region's MemStore usage.
1592 Regions will have their MemStores flushed until the overall MemStore usage drops
1593 to or slightly below `hbase.regionserver.global.memstore.lowerLimit`.
1595 . When the number of WAL log entries in a given region server's WAL reaches the
1596 value specified in `hbase.regionserver.max.logs`, MemStores from various regions
1597 will be flushed out to disk to reduce the number of logs in the WAL.
1599 The flush order is based on time.
1601 Regions with the oldest MemStores are flushed first until WAL count drops below
1602 `hbase.regionserver.max.logs`.
1607 * When a client issues a scan against a table, HBase generates `RegionScanner` objects, one per region, to serve the scan request.
1608 * The `RegionScanner` object contains a list of `StoreScanner` objects, one per column family.
1609 * Each `StoreScanner` object further contains a list of `StoreFileScanner` objects, corresponding to each StoreFile and HFile of the corresponding column family, and a list of `KeyValueScanner` objects for the MemStore.
1610 * The two lists are merged into one, which is sorted in ascending order with the scan object for the MemStore at the end of the list.
1611 * When a `StoreFileScanner` object is constructed, it is associated with a `MultiVersionConcurrencyControl` read point, which is the current `memstoreTS`, filtering out any new updates beyond the read point.
1614 ==== StoreFile (HFile)
1616 StoreFiles are where your data lives.
1620 The _HFile_ file format is based on the SSTable file described in the link:http://research.google.com/archive/bigtable.html[BigTable [2006]] paper and on Hadoop's link:https://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/io/file/tfile/TFile.html[TFile] (The unit test suite and the compression harness were taken directly from TFile). Schubert Zhang's blog post on link:http://cloudepr.blogspot.com/2009/09/hfile-block-indexed-file-format-to.html[HFile: A Block-Indexed File Format to Store Sorted Key-Value Pairs] makes for a thorough introduction to HBase's HFile.
1621 Matteo Bertozzi has also put up a helpful description, link:http://th30z.blogspot.com/2011/02/hbase-io-hfile.html?spref=tw[HBase I/O: HFile].
1623 For more information, see the HFile source code.
1624 Also see <<hfilev2>> for information about the HFile v2 format that was included in 0.92.
1629 To view a textualized version of HFile content, you can use the `org.apache.hadoop.hbase.io.hfile.HFile` tool.
1630 Type the following to see usage:
1634 $ ${HBASE_HOME}/bin/hbase org.apache.hadoop.hbase.io.hfile.HFile
1636 For example, to view the content of the file _hdfs://10.81.47.41:8020/hbase/default/TEST/1418428042/DSMP/4759508618286845475_, type the following:
1639 $ ${HBASE_HOME}/bin/hbase org.apache.hadoop.hbase.io.hfile.HFile -v -f hdfs://10.81.47.41:8020/hbase/default/TEST/1418428042/DSMP/4759508618286845475
1641 If you leave off the option -v to see just a summary on the HFile.
1642 See usage for other things to do with the `HFile` tool.
1645 ===== StoreFile Directory Structure on HDFS
1647 For more information of what StoreFiles look like on HDFS with respect to the directory structure, see <<trouble.namenode.hbase.objects>>.
1652 StoreFiles are composed of blocks.
1653 The blocksize is configured on a per-ColumnFamily basis.
1655 Compression happens at the block level within StoreFiles.
1656 For more information on compression, see <<compression>>.
1658 For more information on blocks, see the HFileBlock source code.
1663 The KeyValue class is the heart of data storage in HBase.
1664 KeyValue wraps a byte array and takes offsets and lengths into the passed array which specify where to start interpreting the content as KeyValue.
1666 The KeyValue format inside a byte array is:
1673 The Key is further decomposed as:
1676 * row (i.e., the rowkey)
1677 * columnfamilylength
1681 * keytype (e.g., Put, Delete, DeleteColumn, DeleteFamily)
1683 KeyValue instances are _not_ split across blocks.
1684 For example, if there is an 8 MB KeyValue, even if the block-size is 64kb this KeyValue will be read in as a coherent block.
1685 For more information, see the KeyValue source code.
1687 [[keyvalue.example]]
1690 To emphasize the points above, examine what happens with two Puts for two different columns for the same row:
1692 * Put #1: `rowkey=row1, cf:attr1=value1`
1693 * Put #2: `rowkey=row1, cf:attr2=value2`
1695 Even though these are for the same row, a KeyValue is created for each column:
1697 Key portion for Put #1:
1699 * `rowlength ------------> 4`
1700 * `row ------------------> row1`
1701 * `columnfamilylength ---> 2`
1702 * `columnfamily ---------> cf`
1703 * `columnqualifier ------> attr1`
1704 * `timestamp ------------> server time of Put`
1705 * `keytype --------------> Put`
1707 Key portion for Put #2:
1709 * `rowlength ------------> 4`
1710 * `row ------------------> row1`
1711 * `columnfamilylength ---> 2`
1712 * `columnfamily ---------> cf`
1713 * `columnqualifier ------> attr2`
1714 * `timestamp ------------> server time of Put`
1715 * `keytype --------------> Put`
1717 It is critical to understand that the rowkey, ColumnFamily, and column (aka columnqualifier) are embedded within the KeyValue instance.
1718 The longer these identifiers are, the bigger the KeyValue is.
1723 .Ambiguous Terminology
1724 * A _StoreFile_ is a facade of HFile.
1725 In terms of compaction, use of StoreFile seems to have prevailed in the past.
1726 * A _Store_ is the same thing as a ColumnFamily.
1727 StoreFiles are related to a Store, or ColumnFamily.
1728 * If you want to read more about StoreFiles versus HFiles and Stores versus ColumnFamilies, see link:https://issues.apache.org/jira/browse/HBASE-11316[HBASE-11316].
1730 When the MemStore reaches a given size (`hbase.hregion.memstore.flush.size`), it flushes its contents to a StoreFile.
1731 The number of StoreFiles in a Store increases over time. _Compaction_ is an operation which reduces the number of StoreFiles in a Store, by merging them together, in order to increase performance on read operations.
1732 Compactions can be resource-intensive to perform, and can either help or hinder performance depending on many factors.
1734 Compactions fall into two categories: minor and major.
1735 Minor and major compactions differ in the following ways.
1737 _Minor compactions_ usually select a small number of small, adjacent StoreFiles and rewrite them as a single StoreFile.
1738 Minor compactions do not drop (filter out) deletes or expired versions, because of potential side effects.
1739 See <<compaction.and.deletes>> and <<compaction.and.versions>> for information on how deletes and versions are handled in relation to compactions.
1740 The end result of a minor compaction is fewer, larger StoreFiles for a given Store.
1742 The end result of a _major compaction_ is a single StoreFile per Store.
1743 Major compactions also process delete markers and max versions.
1744 See <<compaction.and.deletes>> and <<compaction.and.versions>> for information on how deletes and versions are handled in relation to compactions.
1746 [[compaction.and.deletes]]
1747 .Compaction and Deletions
1748 When an explicit deletion occurs in HBase, the data is not actually deleted.
1749 Instead, a _tombstone_ marker is written.
1750 The tombstone marker prevents the data from being returned with queries.
1751 During a major compaction, the data is actually deleted, and the tombstone marker is removed from the StoreFile.
1752 If the deletion happens because of an expired TTL, no tombstone is created.
1753 Instead, the expired data is filtered out and is not written back to the compacted StoreFile.
1755 [[compaction.and.versions]]
1756 .Compaction and Versions
1757 When you create a Column Family, you can specify the maximum number of versions to keep, by specifying `HColumnDescriptor.setMaxVersions(int versions)`.
1758 The default value is `3`.
1759 If more versions than the specified maximum exist, the excess versions are filtered out and not written back to the compacted StoreFile.
1761 .Major Compactions Can Impact Query Results
1764 In some situations, older versions can be inadvertently resurrected if a newer version is explicitly deleted.
1765 See <<major.compactions.change.query.results>> for a more in-depth explanation.
1766 This situation is only possible before the compaction finishes.
1769 In theory, major compactions improve performance.
1770 However, on a highly loaded system, major compactions can require an inappropriate number of resources and adversely affect performance.
1771 In a default configuration, major compactions are scheduled automatically to run once in a 7-day period.
1772 This is sometimes inappropriate for systems in production.
1773 You can manage major compactions manually.
1774 See <<managed.compactions>>.
1776 Compactions do not perform region merges.
1777 See <<ops.regionmgt.merge>> for more information on region merging.
1779 [[compaction.file.selection]]
1780 ===== Compaction Policy - HBase 0.96.x and newer
1782 Compacting large StoreFiles, or too many StoreFiles at once, can cause more IO load than your cluster is able to handle without causing performance problems.
1783 The method by which HBase selects which StoreFiles to include in a compaction (and whether the compaction is a minor or major compaction) is called the _compaction policy_.
1785 Prior to HBase 0.96.x, there was only one compaction policy.
1786 That original compaction policy is still available as `RatioBasedCompactionPolicy`. The new compaction default policy, called `ExploringCompactionPolicy`, was subsequently backported to HBase 0.94 and HBase 0.95, and is the default in HBase 0.96 and newer.
1787 It was implemented in link:https://issues.apache.org/jira/browse/HBASE-7842[HBASE-7842].
1788 In short, `ExploringCompactionPolicy` attempts to select the best possible set of StoreFiles to compact with the least amount of work, while the `RatioBasedCompactionPolicy` selects the first set that meets the criteria.
1790 Regardless of the compaction policy used, file selection is controlled by several configurable parameters and happens in a multi-step approach.
1791 These parameters will be explained in context, and then will be given in a table which shows their descriptions, defaults, and implications of changing them.
1793 [[compaction.being.stuck]]
1796 When the MemStore gets too large, it needs to flush its contents to a StoreFile.
1797 However, Stores are configured with a bound on the number StoreFiles,
1798 `hbase.hstore.blockingStoreFiles`, and if in excess, the MemStore flush must wait
1799 until the StoreFile count is reduced by one or more compactions. If the MemStore
1800 is too large and the number of StoreFiles is also too high, the algorithm is said
1801 to be "stuck". By default we'll wait on compactions up to
1802 `hbase.hstore.blockingWaitTime` milliseconds. If this period expires, we'll flush
1803 anyways even though we are in excess of the
1804 `hbase.hstore.blockingStoreFiles` count.
1806 Upping the `hbase.hstore.blockingStoreFiles` count will allow flushes to happen
1807 but a Store with many StoreFiles in will likely have higher read latencies. Try to
1808 figure why Compactions are not keeping up. Is it a write spurt that is bringing
1809 about this situation or is a regular occurance and the cluster is under-provisioned
1810 for the volume of writes?
1812 [[exploringcompaction.policy]]
1813 ====== The ExploringCompactionPolicy Algorithm
1815 The ExploringCompactionPolicy algorithm considers each possible set of adjacent StoreFiles before choosing the set where compaction will have the most benefit.
1817 One situation where the ExploringCompactionPolicy works especially well is when you are bulk-loading data and the bulk loads create larger StoreFiles than the StoreFiles which are holding data older than the bulk-loaded data.
1818 This can "trick" HBase into choosing to perform a major compaction each time a compaction is needed, and cause a lot of extra overhead.
1819 With the ExploringCompactionPolicy, major compactions happen much less frequently because minor compactions are more efficient.
1821 In general, ExploringCompactionPolicy is the right choice for most situations, and thus is the default compaction policy.
1822 You can also use ExploringCompactionPolicy along with <<ops.stripe>>.
1824 The logic of this policy can be examined in hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/compactions/ExploringCompactionPolicy.java.
1825 The following is a walk-through of the logic of the ExploringCompactionPolicy.
1828 . Make a list of all existing StoreFiles in the Store.
1829 The rest of the algorithm filters this list to come up with the subset of HFiles which will be chosen for compaction.
1830 . If this was a user-requested compaction, attempt to perform the requested compaction type, regardless of what would normally be chosen.
1831 Note that even if the user requests a major compaction, it may not be possible to perform a major compaction.
1832 This may be because not all StoreFiles in the Column Family are available to compact or because there are too many Stores in the Column Family.
1833 . Some StoreFiles are automatically excluded from consideration.
1836 * StoreFiles that are larger than `hbase.hstore.compaction.max.size`
1837 * StoreFiles that were created by a bulk-load operation which explicitly excluded compaction.
1838 You may decide to exclude StoreFiles resulting from bulk loads, from compaction.
1839 To do this, specify the `hbase.mapreduce.hfileoutputformat.compaction.exclude` parameter during the bulk load operation.
1841 . Iterate through the list from step 1, and make a list of all potential sets of StoreFiles to compact together.
1842 A potential set is a grouping of `hbase.hstore.compaction.min` contiguous StoreFiles in the list.
1843 For each set, perform some sanity-checking and figure out whether this is the best compaction that could be done:
1845 * If the number of StoreFiles in this set (not the size of the StoreFiles) is fewer than `hbase.hstore.compaction.min` or more than `hbase.hstore.compaction.max`, take it out of consideration.
1846 * Compare the size of this set of StoreFiles with the size of the smallest possible compaction that has been found in the list so far.
1847 If the size of this set of StoreFiles represents the smallest compaction that could be done, store it to be used as a fall-back if the algorithm is "stuck" and no StoreFiles would otherwise be chosen.
1848 See <<compaction.being.stuck>>.
1849 * Do size-based sanity checks against each StoreFile in this set of StoreFiles.
1850 ** If the size of this StoreFile is larger than `hbase.hstore.compaction.max.size`, take it out of consideration.
1851 ** If the size is greater than or equal to `hbase.hstore.compaction.min.size`, sanity-check it against the file-based ratio to see whether it is too large to be considered.
1853 The sanity-checking is successful if:
1854 ** There is only one StoreFile in this set, or
1855 ** For each StoreFile, its size multiplied by `hbase.hstore.compaction.ratio` (or `hbase.hstore.compaction.ratio.offpeak` if off-peak hours are configured and it is during off-peak hours) is less than the sum of the sizes of the other HFiles in the set.
1857 . If this set of StoreFiles is still in consideration, compare it to the previously-selected best compaction.
1858 If it is better, replace the previously-selected best compaction with this one.
1859 . When the entire list of potential compactions has been processed, perform the best compaction that was found.
1860 If no StoreFiles were selected for compaction, but there are multiple StoreFiles, assume the algorithm is stuck (see <<compaction.being.stuck>>) and if so, perform the smallest compaction that was found in step 3.
1862 [[compaction.ratiobasedcompactionpolicy.algorithm]]
1863 ====== RatioBasedCompactionPolicy Algorithm
1865 The RatioBasedCompactionPolicy was the only compaction policy prior to HBase 0.96, though ExploringCompactionPolicy has now been backported to HBase 0.94 and 0.95.
1866 To use the RatioBasedCompactionPolicy rather than the ExploringCompactionPolicy, set `hbase.hstore.defaultengine.compactionpolicy.class` to `RatioBasedCompactionPolicy` in the _hbase-site.xml_ file.
1867 To switch back to the ExploringCompactionPolicy, remove the setting from the _hbase-site.xml_.
1869 The following section walks you through the algorithm used to select StoreFiles for compaction in the RatioBasedCompactionPolicy.
1872 . The first phase is to create a list of all candidates for compaction.
1873 A list is created of all StoreFiles not already in the compaction queue, and all StoreFiles newer than the newest file that is currently being compacted.
1874 This list of StoreFiles is ordered by the sequence ID.
1875 The sequence ID is generated when a Put is appended to the write-ahead log (WAL), and is stored in the metadata of the HFile.
1876 . Check to see if the algorithm is stuck (see <<compaction.being.stuck>>, and if so, a major compaction is forced.
1877 This is a key area where <<exploringcompaction.policy>> is often a better choice than the RatioBasedCompactionPolicy.
1878 . If the compaction was user-requested, try to perform the type of compaction that was requested.
1879 Note that a major compaction may not be possible if all HFiles are not available for compaction or if too many StoreFiles exist (more than `hbase.hstore.compaction.max`).
1880 . Some StoreFiles are automatically excluded from consideration.
1883 * StoreFiles that are larger than `hbase.hstore.compaction.max.size`
1884 * StoreFiles that were created by a bulk-load operation which explicitly excluded compaction.
1885 You may decide to exclude StoreFiles resulting from bulk loads, from compaction.
1886 To do this, specify the `hbase.mapreduce.hfileoutputformat.compaction.exclude` parameter during the bulk load operation.
1888 . The maximum number of StoreFiles allowed in a major compaction is controlled by the `hbase.hstore.compaction.max` parameter.
1889 If the list contains more than this number of StoreFiles, a minor compaction is performed even if a major compaction would otherwise have been done.
1890 However, a user-requested major compaction still occurs even if there are more than `hbase.hstore.compaction.max` StoreFiles to compact.
1891 . If the list contains fewer than `hbase.hstore.compaction.min` StoreFiles to compact, a minor compaction is aborted.
1892 Note that a major compaction can be performed on a single HFile.
1893 Its function is to remove deletes and expired versions, and reset locality on the StoreFile.
1894 . The value of the `hbase.hstore.compaction.ratio` parameter is multiplied by the sum of StoreFiles smaller than a given file, to determine whether that StoreFile is selected for compaction during a minor compaction.
1895 For instance, if hbase.hstore.compaction.ratio is 1.2, FileX is 5MB, FileY is 2MB, and FileZ is 3MB:
1898 5 <= 1.2 x (2 + 3) or 5 <= 6
1901 In this scenario, FileX is eligible for minor compaction.
1902 If FileX were 7MB, it would not be eligible for minor compaction.
1903 This ratio favors smaller StoreFile.
1904 You can configure a different ratio for use in off-peak hours, using the parameter `hbase.hstore.compaction.ratio.offpeak`, if you also configure `hbase.offpeak.start.hour` and `hbase.offpeak.end.hour`.
1906 . If the last major compaction was too long ago and there is more than one StoreFile to be compacted, a major compaction is run, even if it would otherwise have been minor.
1907 By default, the maximum time between major compactions is 7 days, plus or minus a 4.8 hour period, and determined randomly within those parameters.
1908 Prior to HBase 0.96, the major compaction period was 24 hours.
1909 See `hbase.hregion.majorcompaction` in the table below to tune or disable time-based major compactions.
1911 [[compaction.parameters]]
1912 ====== Parameters Used by Compaction Algorithm
1914 This table contains the main configuration parameters for compaction.
1915 This list is not exhaustive.
1916 To tune these parameters from the defaults, edit the _hbase-default.xml_ file.
1917 For a full list of all configuration parameters available, see <<config.files,config.files>>
1919 `hbase.hstore.compaction.min`::
1920 The minimum number of StoreFiles which must be eligible for compaction before compaction can run.
1921 The goal of tuning `hbase.hstore.compaction.min` is to avoid ending up with too many tiny StoreFiles
1922 to compact. Setting this value to 2 would cause a minor compaction each time you have two StoreFiles
1923 in a Store, and this is probably not appropriate. If you set this value too high, all the other
1924 values will need to be adjusted accordingly. For most cases, the default value is appropriate.
1925 In previous versions of HBase, the parameter `hbase.hstore.compaction.min` was called
1926 `hbase.hstore.compactionThreshold`.
1930 `hbase.hstore.compaction.max`::
1931 The maximum number of StoreFiles which will be selected for a single minor compaction,
1932 regardless of the number of eligible StoreFiles. Effectively, the value of
1933 `hbase.hstore.compaction.max` controls the length of time it takes a single
1934 compaction to complete. Setting it larger means that more StoreFiles are included
1935 in a compaction. For most cases, the default value is appropriate.
1939 `hbase.hstore.compaction.min.size`::
1940 A StoreFile smaller than this size will always be eligible for minor compaction.
1941 StoreFiles this size or larger are evaluated by `hbase.hstore.compaction.ratio`
1942 to determine if they are eligible. Because this limit represents the "automatic
1943 include" limit for all StoreFiles smaller than this value, this value may need
1944 to be reduced in write-heavy environments where many files in the 1-2 MB range
1945 are being flushed, because every StoreFile will be targeted for compaction and
1946 the resulting StoreFiles may still be under the minimum size and require further
1947 compaction. If this parameter is lowered, the ratio check is triggered more quickly.
1948 This addressed some issues seen in earlier versions of HBase but changing this
1949 parameter is no longer necessary in most situations.
1953 `hbase.hstore.compaction.max.size`::
1954 A StoreFile larger than this size will be excluded from compaction. The effect of
1955 raising `hbase.hstore.compaction.max.size` is fewer, larger StoreFiles that do not
1956 get compacted often. If you feel that compaction is happening too often without
1957 much benefit, you can try raising this value.
1959 *Default*: `Long.MAX_VALUE`
1961 `hbase.hstore.compaction.ratio`::
1962 For minor compaction, this ratio is used to determine whether a given StoreFile
1963 which is larger than `hbase.hstore.compaction.min.size` is eligible for compaction.
1964 Its effect is to limit compaction of large StoreFile. The value of
1965 `hbase.hstore.compaction.ratio` is expressed as a floating-point decimal.
1967 * A large ratio, such as 10, will produce a single giant StoreFile. Conversely,
1968 a value of .25, will produce behavior similar to the BigTable compaction algorithm,
1969 producing four StoreFiles.
1970 * A moderate value of between 1.0 and 1.4 is recommended. When tuning this value,
1971 you are balancing write costs with read costs. Raising the value (to something like
1972 1.4) will have more write costs, because you will compact larger StoreFiles.
1973 However, during reads, HBase will need to seek through fewer StoreFiles to
1974 accomplish the read. Consider this approach if you cannot take advantage of <<blooms>>.
1975 * Alternatively, you can lower this value to something like 1.0 to reduce the
1976 background cost of writes, and use to limit the number of StoreFiles touched
1977 during reads. For most cases, the default value is appropriate.
1981 `hbase.hstore.compaction.ratio.offpeak`::
1982 The compaction ratio used during off-peak compactions, if off-peak hours are
1983 also configured (see below). Expressed as a floating-point decimal. This allows
1984 for more aggressive (or less aggressive, if you set it lower than
1985 `hbase.hstore.compaction.ratio`) compaction during a set time period. Ignored
1986 if off-peak is disabled (default). This works the same as
1987 `hbase.hstore.compaction.ratio`.
1991 `hbase.offpeak.start.hour`::
1992 The start of off-peak hours, expressed as an integer between 0 and 23, inclusive.
1993 Set to -1 to disable off-peak.
1995 *Default*: `-1` (disabled)
1997 `hbase.offpeak.end.hour`::
1998 The end of off-peak hours, expressed as an integer between 0 and 23, inclusive.
1999 Set to -1 to disable off-peak.
2001 *Default*: `-1` (disabled)
2003 `hbase.regionserver.thread.compaction.throttle`::
2004 There are two different thread pools for compactions, one for large compactions
2005 and the other for small compactions. This helps to keep compaction of lean tables
2006 (such as `hbase:meta`) fast. If a compaction is larger than this threshold,
2007 it goes into the large compaction pool. In most cases, the default value is
2010 *Default*: `2 x hbase.hstore.compaction.max x hbase.hregion.memstore.flush.size`
2011 (which defaults to `128`)
2013 `hbase.hregion.majorcompaction`::
2014 Time between major compactions, expressed in milliseconds. Set to 0 to disable
2015 time-based automatic major compactions. User-requested and size-based major
2016 compactions will still run. This value is multiplied by
2017 `hbase.hregion.majorcompaction.jitter` to cause compaction to start at a
2018 somewhat-random time during a given window of time.
2020 *Default*: 7 days (`604800000` milliseconds)
2022 `hbase.hregion.majorcompaction.jitter`::
2023 A multiplier applied to hbase.hregion.majorcompaction to cause compaction to
2024 occur a given amount of time either side of `hbase.hregion.majorcompaction`.
2025 The smaller the number, the closer the compactions will happen to the
2026 `hbase.hregion.majorcompaction` interval. Expressed as a floating-point decimal.
2030 [[compaction.file.selection.old]]
2031 ===== Compaction File Selection
2036 This section has been preserved for historical reasons and refers to the way compaction worked prior to HBase 0.96.x.
2037 You can still use this behavior if you enable <<compaction.ratiobasedcompactionpolicy.algorithm>>. For information on the way that compactions work in HBase 0.96.x and later, see <<compaction>>.
2040 To understand the core algorithm for StoreFile selection, there is some ASCII-art in the Store source code that will serve as useful reference.
2042 It has been copied below:
2051 * --|-|- |-|- |-|---_-------_------- minCompactSize
2052 * | | | | | | | | _ | |
2053 * | | | | | | | | | | | |
2054 * | | | | | | | | | | | |
2058 * `hbase.hstore.compaction.ratio` Ratio used in compaction file selection algorithm (default 1.2f).
2059 * `hbase.hstore.compaction.min` (in HBase v 0.90 this is called `hbase.hstore.compactionThreshold`) (files) Minimum number of StoreFiles per Store to be selected for a compaction to occur (default 2).
2060 * `hbase.hstore.compaction.max` (files) Maximum number of StoreFiles to compact per minor compaction (default 10).
2061 * `hbase.hstore.compaction.min.size` (bytes) Any StoreFile smaller than this setting with automatically be a candidate for compaction.
2062 Defaults to `hbase.hregion.memstore.flush.size` (128 mb).
2063 * `hbase.hstore.compaction.max.size` (.92) (bytes) Any StoreFile larger than this setting with automatically be excluded from compaction (default Long.MAX_VALUE).
2065 The minor compaction StoreFile selection logic is size based, and selects a file for compaction when the `file <= sum(smaller_files) * hbase.hstore.compaction.ratio`.
2067 [[compaction.file.selection.example1]]
2068 ====== Minor Compaction File Selection - Example #1 (Basic Example)
2070 This example mirrors an example from the unit test `TestCompactSelection`.
2072 * `hbase.hstore.compaction.ratio` = 1.0f
2073 * `hbase.hstore.compaction.min` = 3 (files)
2074 * `hbase.hstore.compaction.max` = 5 (files)
2075 * `hbase.hstore.compaction.min.size` = 10 (bytes)
2076 * `hbase.hstore.compaction.max.size` = 1000 (bytes)
2078 The following StoreFiles exist: 100, 50, 23, 12, and 12 bytes apiece (oldest to newest). With the above parameters, the files that would be selected for minor compaction are 23, 12, and 12.
2082 * 100 -> No, because sum(50, 23, 12, 12) * 1.0 = 97.
2083 * 50 -> No, because sum(23, 12, 12) * 1.0 = 47.
2084 * 23 -> Yes, because sum(12, 12) * 1.0 = 24.
2085 * 12 -> Yes, because the previous file has been included, and because this does not exceed the max-file limit of 5
2086 * 12 -> Yes, because the previous file had been included, and because this does not exceed the max-file limit of 5.
2088 [[compaction.file.selection.example2]]
2089 ====== Minor Compaction File Selection - Example #2 (Not Enough Files ToCompact)
2091 This example mirrors an example from the unit test `TestCompactSelection`.
2093 * `hbase.hstore.compaction.ratio` = 1.0f
2094 * `hbase.hstore.compaction.min` = 3 (files)
2095 * `hbase.hstore.compaction.max` = 5 (files)
2096 * `hbase.hstore.compaction.min.size` = 10 (bytes)
2097 * `hbase.hstore.compaction.max.size` = 1000 (bytes)
2099 The following StoreFiles exist: 100, 25, 12, and 12 bytes apiece (oldest to newest). With the above parameters, no compaction will be started.
2103 * 100 -> No, because sum(25, 12, 12) * 1.0 = 47
2104 * 25 -> No, because sum(12, 12) * 1.0 = 24
2105 * 12 -> No. Candidate because sum(12) * 1.0 = 12, there are only 2 files to compact and that is less than the threshold of 3
2106 * 12 -> No. Candidate because the previous StoreFile was, but there are not enough files to compact
2108 [[compaction.file.selection.example3]]
2109 ====== Minor Compaction File Selection - Example #3 (Limiting Files To Compact)
2111 This example mirrors an example from the unit test `TestCompactSelection`.
2113 * `hbase.hstore.compaction.ratio` = 1.0f
2114 * `hbase.hstore.compaction.min` = 3 (files)
2115 * `hbase.hstore.compaction.max` = 5 (files)
2116 * `hbase.hstore.compaction.min.size` = 10 (bytes)
2117 * `hbase.hstore.compaction.max.size` = 1000 (bytes)
2119 The following StoreFiles exist: 7, 6, 5, 4, 3, 2, and 1 bytes apiece (oldest to newest). With the above parameters, the files that would be selected for minor compaction are 7, 6, 5, 4, 3.
2123 * 7 -> Yes, because sum(6, 5, 4, 3, 2, 1) * 1.0 = 21.
2124 Also, 7 is less than the min-size
2125 * 6 -> Yes, because sum(5, 4, 3, 2, 1) * 1.0 = 15.
2126 Also, 6 is less than the min-size.
2127 * 5 -> Yes, because sum(4, 3, 2, 1) * 1.0 = 10.
2128 Also, 5 is less than the min-size.
2129 * 4 -> Yes, because sum(3, 2, 1) * 1.0 = 6.
2130 Also, 4 is less than the min-size.
2131 * 3 -> Yes, because sum(2, 1) * 1.0 = 3.
2132 Also, 3 is less than the min-size.
2134 Candidate because previous file was selected and 2 is less than the min-size, but the max-number of files to compact has been reached.
2136 Candidate because previous file was selected and 1 is less than the min-size, but max-number of files to compact has been reached.
2138 [[compaction.config.impact]]
2139 .Impact of Key Configuration Options
2141 NOTE: This information is now included in the configuration parameter table in <<compaction.parameters>>.
2144 ===== Date Tiered Compaction
2146 Date tiered compaction is a date-aware store file compaction strategy that is beneficial for time-range scans for time-series data.
2148 [[ops.date.tiered.when]]
2149 ===== When To Use Date Tiered Compactions
2151 Consider using Date Tiered Compaction for reads for limited time ranges, especially scans of recent data
2155 * random gets without a limited time range
2156 * frequent deletes and updates
2157 * Frequent out of order data writes creating long tails, especially writes with future timestamps
2158 * frequent bulk loads with heavily overlapping time ranges
2160 .Performance Improvements
2161 Performance testing has shown that the performance of time-range scans improve greatly for limited time ranges, especially scans of recent data.
2163 [[ops.date.tiered.enable]]
2164 ====== Enabling Date Tiered Compaction
2166 You can enable Date Tiered compaction for a table or a column family, by setting its `hbase.hstore.engine.class` to `org.apache.hadoop.hbase.regionserver.DateTieredStoreEngine`.
2168 You also need to set `hbase.hstore.blockingStoreFiles` to a high number, such as 60, if using all default settings, rather than the default value of 12). Use 1.5~2 x projected file count if changing the parameters, Projected file count = windows per tier x tier count + incoming window min + files older than max age
2170 You also need to set `hbase.hstore.compaction.max` to the same value as `hbase.hstore.blockingStoreFiles` to unblock major compaction.
2172 .Procedure: Enable Date Tiered Compaction
2173 . Run one of following commands in the HBase shell.
2174 Replace the table name `orders_table` with the name of your table.
2178 alter 'orders_table', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.DateTieredStoreEngine', 'hbase.hstore.blockingStoreFiles' => '60', 'hbase.hstore.compaction.min'=>'2', 'hbase.hstore.compaction.max'=>'60'}
2179 alter 'orders_table', {NAME => 'blobs_cf', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.DateTieredStoreEngine', 'hbase.hstore.blockingStoreFiles' => '60', 'hbase.hstore.compaction.min'=>'2', 'hbase.hstore.compaction.max'=>'60'}}
2180 create 'orders_table', 'blobs_cf', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.DateTieredStoreEngine', 'hbase.hstore.blockingStoreFiles' => '60', 'hbase.hstore.compaction.min'=>'2', 'hbase.hstore.compaction.max'=>'60'}
2183 . Configure other options if needed.
2184 See <<ops.date.tiered.config>> for more information.
2186 .Procedure: Disable Date Tiered Compaction
2187 . Set the `hbase.hstore.engine.class` option to either nil or `org.apache.hadoop.hbase.regionserver.DefaultStoreEngine`.
2188 Either option has the same effect.
2189 Make sure you set the other options you changed to the original settings too.
2193 alter 'orders_table', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.DefaultStoreEngine', 'hbase.hstore.blockingStoreFiles' => '12', 'hbase.hstore.compaction.min'=>'6', 'hbase.hstore.compaction.max'=>'12'}}
2196 When you change the store engine either way, a major compaction will likely be performed on most regions.
2197 This is not necessary on new tables.
2199 [[ops.date.tiered.config]]
2200 ====== Configuring Date Tiered Compaction
2202 Each of the settings for date tiered compaction should be configured at the table or column family level.
2203 If you use HBase shell, the general command pattern is as follows:
2207 alter 'orders_table', CONFIGURATION => {'key' => 'value', ..., 'key' => 'value'}}
2210 [[ops.date.tiered.config.parameters]]
2213 You can configure your date tiers by changing the settings for the following parameters:
2215 .Date Tier Parameters
2216 [cols="1,1a", frame="all", options="header"]
2221 |`hbase.hstore.compaction.date.tiered.max.storefile.age.millis`
2222 |Files with max-timestamp smaller than this will no longer be compacted.Default at Long.MAX_VALUE.
2224 | `hbase.hstore.compaction.date.tiered.base.window.millis`
2225 | Base window size in milliseconds. Default at 6 hours.
2227 | `hbase.hstore.compaction.date.tiered.windows.per.tier`
2228 | Number of windows per tier. Default at 4.
2230 | `hbase.hstore.compaction.date.tiered.incoming.window.min`
2231 | Minimal number of files to compact in the incoming window. Set it to expected number of files in the window to avoid wasteful compaction. Default at 6.
2233 | `hbase.hstore.compaction.date.tiered.window.policy.class`
2234 | The policy to select store files within the same time window. It doesn’t apply to the incoming window. Default at exploring compaction. This is to avoid wasteful compaction.
2237 [[ops.date.tiered.config.compaction.throttler]]
2238 .Compaction Throttler
2240 With tiered compaction all servers in the cluster will promote windows to higher tier at the same time, so using a compaction throttle is recommended:
2241 Set `hbase.regionserver.throughput.controller` to `org.apache.hadoop.hbase.regionserver.compactions.PressureAwareCompactionThroughputController`.
2243 NOTE: For more information about date tiered compaction, please refer to the design specification at https://docs.google.com/document/d/1_AmlNb2N8Us1xICsTeGDLKIqL6T-oHoRLZ323MG_uy8
2245 ===== Experimental: Stripe Compactions
2247 Stripe compactions is an experimental feature added in HBase 0.98 which aims to improve compactions for large regions or non-uniformly distributed row keys.
2248 In order to achieve smaller and/or more granular compactions, the StoreFiles within a region are maintained separately for several row-key sub-ranges, or "stripes", of the region.
2249 The stripes are transparent to the rest of HBase, so other operations on the HFiles or data work without modification.
2251 Stripe compactions change the HFile layout, creating sub-regions within regions.
2252 These sub-regions are easier to compact, and should result in fewer major compactions.
2253 This approach alleviates some of the challenges of larger regions.
2255 Stripe compaction is fully compatible with <<compaction>> and works in conjunction with either the ExploringCompactionPolicy or RatioBasedCompactionPolicy.
2256 It can be enabled for existing tables, and the table will continue to operate normally if it is disabled later.
2259 ===== When To Use Stripe Compactions
2261 Consider using stripe compaction if you have either of the following:
2264 You can get the positive effects of smaller regions without additional overhead for MemStore and region management overhead.
2265 * Non-uniform keys, such as time dimension in a key.
2266 Only the stripes receiving the new keys will need to compact.
2267 Old data will not compact as often, if at all
2269 .Performance Improvements
2270 Performance testing has shown that the performance of reads improves somewhat, and variability of performance of reads and writes is greatly reduced.
2271 An overall long-term performance improvement is seen on large non-uniform-row key regions, such as a hash-prefixed timestamp key.
2272 These performance gains are the most dramatic on a table which is already large.
2273 It is possible that the performance improvement might extend to region splits.
2275 [[ops.stripe.enable]]
2276 ====== Enabling Stripe Compaction
2278 You can enable stripe compaction for a table or a column family, by setting its `hbase.hstore.engine.class` to `org.apache.hadoop.hbase.regionserver.StripeStoreEngine`.
2279 You also need to set the `hbase.hstore.blockingStoreFiles` to a high number, such as 100 (rather than the default value of 10).
2281 .Procedure: Enable Stripe Compaction
2282 . Run one of following commands in the HBase shell.
2283 Replace the table name `orders_table` with the name of your table.
2287 alter 'orders_table', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.StripeStoreEngine', 'hbase.hstore.blockingStoreFiles' => '100'}
2288 alter 'orders_table', {NAME => 'blobs_cf', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.StripeStoreEngine', 'hbase.hstore.blockingStoreFiles' => '100'}}
2289 create 'orders_table', 'blobs_cf', CONFIGURATION => {'hbase.hstore.engine.class' => 'org.apache.hadoop.hbase.regionserver.StripeStoreEngine', 'hbase.hstore.blockingStoreFiles' => '100'}
2292 . Configure other options if needed.
2293 See <<ops.stripe.config>> for more information.
2296 .Procedure: Disable Stripe Compaction
2297 . Set the `hbase.hstore.engine.class` option to either nil or `org.apache.hadoop.hbase.regionserver.DefaultStoreEngine`.
2298 Either option has the same effect.
2302 alter 'orders_table', CONFIGURATION => {'hbase.hstore.engine.class' => 'rg.apache.hadoop.hbase.regionserver.DefaultStoreEngine'}
2307 When you enable a large table after changing the store engine either way, a major compaction will likely be performed on most regions.
2308 This is not necessary on new tables.
2310 [[ops.stripe.config]]
2311 ====== Configuring Stripe Compaction
2313 Each of the settings for stripe compaction should be configured at the table or column family level.
2314 If you use HBase shell, the general command pattern is as follows:
2318 alter 'orders_table', CONFIGURATION => {'key' => 'value', ..., 'key' => 'value'}}
2321 [[ops.stripe.config.sizing]]
2322 .Region and stripe sizing
2324 You can configure your stripe sizing based upon your region sizing.
2325 By default, your new regions will start with one stripe.
2326 On the next compaction after the stripe has grown too large (16 x MemStore flushes size), it is split into two stripes.
2327 Stripe splitting continues as the region grows, until the region is large enough to split.
2329 You can improve this pattern for your own data.
2330 A good rule is to aim for a stripe size of at least 1 GB, and about 8-12 stripes for uniform row keys.
2331 For example, if your regions are 30 GB, 12 x 2.5 GB stripes might be a good starting point.
2333 .Stripe Sizing Settings
2334 [cols="1,1a", frame="all", options="header"]
2339 |`hbase.store.stripe.initialStripeCount`
2340 |The number of stripes to create when stripe compaction is enabled. You can use it as follows:
2342 * For relatively uniform row keys, if you know the approximate
2343 target number of stripes from the above, you can avoid some
2344 splitting overhead by starting with several stripes (2, 5, 10...).
2345 If the early data is not representative of overall row key
2346 distribution, this will not be as efficient.
2348 * For existing tables with a large amount of data, this setting
2349 will effectively pre-split your stripes.
2351 * For keys such as hash-prefixed sequential keys, with more than
2352 one hash prefix per region, pre-splitting may make sense.
2355 | `hbase.store.stripe.sizeToSplit`
2356 | The maximum size a stripe grows before splitting. Use this in
2357 conjunction with `hbase.store.stripe.splitPartCount` to
2358 control the target stripe size (`sizeToSplit = splitPartsCount * target
2359 stripe size`), according to the above sizing considerations.
2361 | `hbase.store.stripe.splitPartCount`
2362 | The number of new stripes to create when splitting a stripe. The default is 2, which is appropriate for most cases. For non-uniform row keys, you can experiment with increasing the number to 3 or 4, to isolate the arriving updates into narrower slice of the region without additional splits being required.
2365 [[ops.stripe.config.memstore]]
2366 .MemStore Size Settings
2368 By default, the flush creates several files from one MemStore, according to existing stripe boundaries and row keys to flush.
2369 This approach minimizes write amplification, but can be undesirable if the MemStore is small and there are many stripes, because the files will be too small.
2371 In this type of situation, you can set `hbase.store.stripe.compaction.flushToL0` to `true`.
2372 This will cause a MemStore flush to create a single file instead.
2373 When at least `hbase.store.stripe.compaction.minFilesL0` such files (by default, 4) accumulate, they will be compacted into striped files.
2375 [[ops.stripe.config.compact]]
2376 .Normal Compaction Configuration and Stripe Compaction
2378 All the settings that apply to normal compactions (see <<compaction.parameters>>) apply to stripe compactions.
2379 The exceptions are the minimum and maximum number of files, which are set to higher values by default because the files in stripes are smaller.
2380 To control these for stripe compactions, use `hbase.store.stripe.compaction.minFiles` and `hbase.store.stripe.compaction.maxFiles`, rather than `hbase.hstore.compaction.min` and `hbase.hstore.compaction.max`.
2385 [[arch.bulk.load.overview]]
2388 HBase includes several methods of loading data into tables.
2389 The most straightforward method is to either use the `TableOutputFormat` class from a MapReduce job, or use the normal client APIs; however, these are not always the most efficient methods.
2391 The bulk load feature uses a MapReduce job to output table data in HBase's internal data format, and then directly loads the generated StoreFiles into a running cluster.
2392 Using bulk load will use less CPU and network resources than simply using the HBase API.
2394 [[arch.bulk.load.limitations]]
2395 === Bulk Load Limitations
2397 As bulk loading bypasses the write path, the WAL doesn't get written to as part of the process.
2398 Replication works by reading the WAL files so it won't see the bulk loaded data – and the same goes for the edits that use `Put.setDurability(SKIP_WAL)`. One way to handle that is to ship the raw files or the HFiles to the other cluster and do the other processing there.
2400 [[arch.bulk.load.arch]]
2401 === Bulk Load Architecture
2403 The HBase bulk load process consists of two main steps.
2405 [[arch.bulk.load.prep]]
2406 ==== Preparing data via a MapReduce job
2408 The first step of a bulk load is to generate HBase data files (StoreFiles) from a MapReduce job using `HFileOutputFormat2`.
2409 This output format writes out data in HBase's internal storage format so that they can be later loaded very efficiently into the cluster.
2411 In order to function efficiently, `HFileOutputFormat2` must be configured such that each output HFile fits within a single region.
2412 In order to do this, jobs whose output will be bulk loaded into HBase use Hadoop's `TotalOrderPartitioner` class to partition the map output into disjoint ranges of the key space, corresponding to the key ranges of the regions in the table.
2414 `HFileOutputFormat2` includes a convenience function, `configureIncrementalLoad()`, which automatically sets up a `TotalOrderPartitioner` based on the current region boundaries of a table.
2416 [[arch.bulk.load.complete]]
2417 ==== Completing the data load
2419 After a data import has been prepared, either by using the `importtsv` tool with the "`importtsv.bulk.output`" option or by some other MapReduce job using the `HFileOutputFormat`, the `completebulkload` tool is used to import the data into the running cluster.
2420 This command line tool iterates through the prepared data files, and for each one determines the region the file belongs to.
2421 It then contacts the appropriate RegionServer which adopts the HFile, moving it into its storage directory and making the data available to clients.
2423 If the region boundaries have changed during the course of bulk load preparation, or between the preparation and completion steps, the `completebulkload` utility will automatically split the data files into pieces corresponding to the new boundaries.
2424 This process is not optimally efficient, so users should take care to minimize the delay between preparing a bulk load and importing it into the cluster, especially if other clients are simultaneously loading data through other means.
2428 $ hadoop jar hbase-server-VERSION.jar completebulkload [-c /path/to/hbase/config/hbase-site.xml] /user/todd/myoutput mytable
2431 The `-c config-file` option can be used to specify a file containing the appropriate hbase parameters (e.g., hbase-site.xml) if not supplied already on the CLASSPATH (In addition, the CLASSPATH must contain the directory that has the zookeeper configuration file if zookeeper is NOT managed by HBase).
2433 NOTE: If the target table does not already exist in HBase, this tool will create the table automatically.
2436 [[arch.bulk.load.also]]
2439 For more information about the referenced utilities, see <<importtsv>> and <<completebulkload>>.
2441 See link:http://blog.cloudera.com/blog/2013/09/how-to-use-hbase-bulk-loading-and-why/[How-to: Use HBase Bulk Loading, and Why] for a recent blog on current state of bulk loading.
2443 [[arch.bulk.load.adv]]
2446 Although the `importtsv` tool is useful in many cases, advanced users may want to generate data programmatically, or import data from other formats.
2447 To get started doing so, dig into `ImportTsv.java` and check the JavaDoc for HFileOutputFormat.
2449 The import step of the bulk load can also be done programmatically.
2450 See the `LoadIncrementalHFiles` class for more information.
2455 As HBase runs on HDFS (and each StoreFile is written as a file on HDFS), it is important to have an understanding of the HDFS Architecture especially in terms of how it stores files, handles failovers, and replicates blocks.
2457 See the Hadoop documentation on link:https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html[HDFS Architecture] for more information.
2462 The NameNode is responsible for maintaining the filesystem metadata.
2463 See the above HDFS Architecture link for more information.
2468 The DataNodes are responsible for storing HDFS blocks.
2469 See the above HDFS Architecture link for more information.
2471 [[arch.timelineconsistent.reads]]
2472 == Timeline-consistent High Available Reads
2474 [[casestudies.timelineconsistent.intro]]
2477 HBase, architecturally, always had the strong consistency guarantee from the start.
2478 All reads and writes are routed through a single region server, which guarantees that all writes happen in an order, and all reads are seeing the most recent committed data.
2481 However, because of this single homing of the reads to a single location, if the server becomes unavailable, the regions of the table that were hosted in the region server become unavailable for some time.
2482 There are three phases in the region recovery process - detection, assignment, and recovery.
2483 Of these, the detection is usually the longest and is presently in the order of 20-30 seconds depending on the ZooKeeper session timeout.
2484 During this time and before the recovery is complete, the clients will not be able to read the region data.
2486 However, for some use cases, either the data may be read-only, or doing reads against some stale data is acceptable.
2487 With timeline-consistent high available reads, HBase can be used for these kind of latency-sensitive use cases where the application can expect to have a time bound on the read completion.
2490 For achieving high availability for reads, HBase provides a feature called _region replication_. In this model, for each region of a table, there will be multiple replicas that are opened in different RegionServers.
2491 By default, the region replication is set to 1, so only a single region replica is deployed and there will not be any changes from the original model.
2492 If region replication is set to 2 or more, then the master will assign replicas of the regions of the table.
2493 The Load Balancer ensures that the region replicas are not co-hosted in the same region servers and also in the same rack (if possible).
2495 All of the replicas for a single region will have a unique replica_id, starting from 0.
2496 The region replica having replica_id==0 is called the primary region, and the others _secondary regions_ or secondaries.
2497 Only the primary can accept writes from the client, and the primary will always contain the latest changes.
2498 Since all writes still have to go through the primary region, the writes are not highly-available (meaning they might block for some time if the region becomes unavailable).
2501 === Timeline Consistency
2503 With this feature, HBase introduces a Consistency definition, which can be provided per read operation (get or scan).
2506 public enum Consistency {
2511 `Consistency.STRONG` is the default consistency model provided by HBase.
2512 In case the table has region replication = 1, or in a table with region replicas but the reads are done with this consistency, the read is always performed by the primary regions, so that there will not be any change from the previous behaviour, and the client always observes the latest data.
2515 In case a read is performed with `Consistency.TIMELINE`, then the read RPC will be sent to the primary region server first.
2516 After a short interval (`hbase.client.primaryCallTimeout.get`, 10ms by default), parallel RPC for secondary region replicas will also be sent if the primary does not respond back.
2517 After this, the result is returned from whichever RPC is finished first.
2518 If the response came back from the primary region replica, we can always know that the data is latest.
2519 For this Result.isStale() API has been added to inspect the staleness.
2520 If the result is from a secondary region, then Result.isStale() will be set to true.
2521 The user can then inspect this field to possibly reason about the data.
2524 In terms of semantics, TIMELINE consistency as implemented by HBase differs from pure eventual consistency in these respects:
2526 * Single homed and ordered updates: Region replication or not, on the write side, there is still only 1 defined replica (primary) which can accept writes.
2527 This replica is responsible for ordering the edits and preventing conflicts.
2528 This guarantees that two different writes are not committed at the same time by different replicas and the data diverges.
2529 With this, there is no need to do read-repair or last-timestamp-wins kind of conflict resolution.
2530 * The secondaries also apply the edits in the order that the primary committed them.
2531 This way the secondaries will contain a snapshot of the primaries data at any point in time.
2532 This is similar to RDBMS replications and even HBase's own multi-datacenter replication, however in a single cluster.
2533 * On the read side, the client can detect whether the read is coming from up-to-date data or is stale data.
2534 Also, the client can issue reads with different consistency requirements on a per-operation basis to ensure its own semantic guarantees.
2535 * The client can still observe edits out-of-order, and can go back in time, if it observes reads from one secondary replica first, then another secondary replica.
2536 There is no stickiness to region replicas or a transaction-id based guarantee.
2537 If required, this can be implemented later though.
2539 .Timeline Consistency
2540 image::timeline_consistency.png[Timeline Consistency]
2542 To better understand the TIMELINE semantics, let's look at the above diagram.
2543 Let's say that there are two clients, and the first one writes x=1 at first, then x=2 and x=3 later.
2544 As above, all writes are handled by the primary region replica.
2545 The writes are saved in the write ahead log (WAL), and replicated to the other replicas asynchronously.
2546 In the above diagram, notice that replica_id=1 received 2 updates, and its data shows that x=2, while the replica_id=2 only received a single update, and its data shows that x=1.
2549 If client1 reads with STRONG consistency, it will only talk with the replica_id=0, and thus is guaranteed to observe the latest value of x=3.
2550 In case of a client issuing TIMELINE consistency reads, the RPC will go to all replicas (after primary timeout) and the result from the first response will be returned back.
2551 Thus the client can see either 1, 2 or 3 as the value of x.
2552 Let's say that the primary region has failed and log replication cannot continue for some time.
2553 If the client does multiple reads with TIMELINE consistency, she can observe x=2 first, then x=1, and so on.
2558 Having secondary regions hosted for read availability comes with some tradeoffs which should be carefully evaluated per use case.
2559 Following are advantages and disadvantages.
2562 * High availability for read-only tables
2563 * High availability for stale reads
2564 * Ability to do very low latency reads with very high percentile (99.9%+) latencies for stale reads
2567 * Double / Triple MemStore usage (depending on region replication count) for tables with region replication > 1
2568 * Increased block cache usage
2569 * Extra network traffic for log replication
2570 * Extra backup RPCs for replicas
2572 To serve the region data from multiple replicas, HBase opens the regions in secondary mode in the region servers.
2573 The regions opened in secondary mode will share the same data files with the primary region replica, however each secondary region replica will have its own MemStore to keep the unflushed data (only primary region can do flushes). Also to serve reads from secondary regions, the blocks of data files may be also cached in the block caches for the secondary regions.
2575 === Where is the code
2576 This feature is delivered in two phases, Phase 1 and 2. The first phase is done in time for HBase-1.0.0 release. Meaning that using HBase-1.0.x, you can use all the features that are marked for Phase 1. Phase 2 is committed in HBase-1.1.0, meaning all HBase versions after 1.1.0 should contain Phase 2 items.
2578 === Propagating writes to region replicas
2579 As discussed above writes only go to the primary region replica. For propagating the writes from the primary region replica to the secondaries, there are two different mechanisms. For read-only tables, you do not need to use any of the following methods. Disabling and enabling the table should make the data available in all region replicas. For mutable tables, you have to use *only* one of the following mechanisms: storefile refresher, or async wal replication. The latter is recommended.
2581 ==== StoreFile Refresher
2582 The first mechanism is store file refresher which is introduced in HBase-1.0+. Store file refresher is a thread per region server, which runs periodically, and does a refresh operation for the store files of the primary region for the secondary region replicas. If enabled, the refresher will ensure that the secondary region replicas see the new flushed, compacted or bulk loaded files from the primary region in a timely manner. However, this means that only flushed data can be read back from the secondary region replicas, and after the refresher is run, making the secondaries lag behind the primary for an a longer time.
2584 For turning this feature on, you should configure `hbase.regionserver.storefile.refresh.period` to a non-zero value. See Configuration section below.
2586 ==== Asnyc WAL replication
2587 The second mechanism for propagation of writes to secondaries is done via “Async WAL Replication” feature and is only available in HBase-1.1+. This works similarly to HBase’s multi-datacenter replication, but instead the data from a region is replicated to the secondary regions. Each secondary replica always receives and observes the writes in the same order that the primary region committed them. In some sense, this design can be thought of as “in-cluster replication”, where instead of replicating to a different datacenter, the data goes to secondary regions to keep secondary region’s in-memory state up to date. The data files are shared between the primary region and the other replicas, so that there is no extra storage overhead. However, the secondary regions will have recent non-flushed data in their memstores, which increases the memory overhead. The primary region writes flush, compaction, and bulk load events to its WAL as well, which are also replicated through wal replication to secondaries. When they observe the flush/compaction or bulk load event, the secondary regions replay the event to pick up the new files and drop the old ones.
2589 Committing writes in the same order as in primary ensures that the secondaries won’t diverge from the primary regions data, but since the log replication is asynchronous, the data might still be stale in secondary regions. Since this feature works as a replication endpoint, the performance and latency characteristics is expected to be similar to inter-cluster replication.
2591 Async WAL Replication is *disabled* by default. You can enable this feature by setting `hbase.region.replica.replication.enabled` to `true`.
2592 Asyn WAL Replication feature will add a new replication peer named `region_replica_replication` as a replication peer when you create a table with region replication > 1 for the first time. Once enabled, if you want to disable this feature, you need to do two actions:
2593 * Set configuration property `hbase.region.replica.replication.enabled` to false in `hbase-site.xml` (see Configuration section below)
2594 * Disable the replication peer named `region_replica_replication` in the cluster using hbase shell or `Admin` class:
2597 hbase> disable_peer 'region_replica_replication'
2601 In both of the write propagation approaches mentioned above, store files of the primary will be opened in secondaries independent of the primary region. So for files that the primary compacted away, the secondaries might still be referring to these files for reading. Both features are using HFileLinks to refer to files, but there is no protection (yet) for guaranteeing that the file will not be deleted prematurely. Thus, as a guard, you should set the configuration property `hbase.master.hfilecleaner.ttl` to a larger value, such as 1 hour to guarantee that you will not receive IOExceptions for requests going to replicas.
2603 === Region replication for META table’s region
2604 Currently, Async WAL Replication is not done for the META table’s WAL. The meta table’s secondary replicas still refreshes themselves from the persistent store files. Hence the `hbase.regionserver.meta.storefile.refresh.period` needs to be set to a certain non-zero value for refreshing the meta store files. Note that this configuration is configured differently than
2605 `hbase.regionserver.storefile.refresh.period`.
2607 === Memory accounting
2608 The secondary region replicas refer to the data files of the primary region replica, but they have their own memstores (in HBase-1.1+) and uses block cache as well. However, one distinction is that the secondary region replicas cannot flush the data when there is memory pressure for their memstores. They can only free up memstore memory when the primary region does a flush and this flush is replicated to the secondary. Since in a region server hosting primary replicas for some regions and secondaries for some others, the secondaries might cause extra flushes to the primary regions in the same host. In extreme situations, there can be no memory left for adding new writes coming from the primary via wal replication. For unblocking this situation (and since secondary cannot flush by itself), the secondary is allowed to do a “store file refresh” by doing a file system list operation to pick up new files from primary, and possibly dropping its memstore. This refresh will only be performed if the memstore size of the biggest secondary region replica is at least `hbase.region.replica.storefile.refresh.memstore.multiplier` (default 4) times bigger than the biggest memstore of a primary replica. One caveat is that if this is performed, the secondary can observe partial row updates across column families (since column families are flushed independently). The default should be good to not do this operation frequently. You can set this value to a large number to disable this feature if desired, but be warned that it might cause the replication to block forever.
2610 === Secondary replica failover
2611 When a secondary region replica first comes online, or fails over, it may have served some edits from its memstore. Since the recovery is handled differently for secondary replicas, the secondary has to ensure that it does not go back in time before it starts serving requests after assignment. For doing that, the secondary waits until it observes a full flush cycle (start flush, commit flush) or a “region open event” replicated from the primary. Until this happens, the secondary region replica will reject all read requests by throwing an IOException with message “The region's reads are disabled”. However, the other replicas will probably still be available to read, thus not causing any impact for the rpc with TIMELINE consistency. To facilitate faster recovery, the secondary region will trigger a flush request from the primary when it is opened. The configuration property `hbase.region.replica.wait.for.primary.flush` (enabled by default) can be used to disable this feature if needed.
2616 === Configuration properties
2618 To use highly available reads, you should set the following properties in `hbase-site.xml` file.
2619 There is no specific configuration to enable or disable region replicas.
2620 Instead you can change the number of region replicas per table to increase or decrease at the table creation or with alter table. The following configuration is for using async wal replication and using meta replicas of 3.
2623 ==== Server side properties
2628 <name>hbase.regionserver.storefile.refresh.period</name>
2631 The period (in milliseconds) for refreshing the store files for the secondary regions. 0 means this feature is disabled. Secondary regions sees new files (from flushes and compactions) from primary once the secondary region refreshes the list of files in the region (there is no notification mechanism). But too frequent refreshes might cause extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL (hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger value is also recommended with this setting.
2636 <name>hbase.regionserver.meta.storefile.refresh.period</name>
2637 <value>300000</value>
2639 The period (in milliseconds) for refreshing the store files for the hbase:meta tables secondary regions. 0 means this feature is disabled. Secondary regions sees new files (from flushes and compactions) from primary once the secondary region refreshes the list of files in the region (there is no notification mechanism). But too frequent refreshes might cause extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL (hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger value is also recommended with this setting. This should be a non-zero number if meta replicas are enabled (via hbase.meta.replica.count set to greater than 1).
2644 <name>hbase.region.replica.replication.enabled</name>
2647 Whether asynchronous WAL replication to the secondary region replicas is enabled or not. If this is enabled, a replication peer named "region_replica_replication" will be created which will tail the logs and replicate the mutations to region replicas for tables that have region replication > 1. If this is enabled once, disabling this replication also requires disabling the replication peer using shell or Admin java class. Replication to secondary region replicas works over standard inter-cluster replication.
2651 <name>hbase.region.replica.replication.memstore.enabled</name>
2654 If you set this to `false`, replicas do not receive memstore updates from
2655 the primary RegionServer. If you set this to `true`, you can still disable
2656 memstore replication on a per-table basis, by setting the table's
2657 `REGION_MEMSTORE_REPLICATION` configuration property to `false`. If
2658 memstore replication is disabled, the secondaries will only receive
2659 updates for events like flushes and bulkloads, and will not have access to
2660 data which the primary has not yet flushed. This preserves the guarantee
2661 of row-level consistency, even when the read requests `Consistency.TIMELINE`.
2666 <name>hbase.master.hfilecleaner.ttl</name>
2667 <value>3600000</value>
2669 The period (in milliseconds) to keep store files in the archive folder before deleting them from the file system.</description>
2673 <name>hbase.meta.replica.count</name>
2676 Region replication count for the meta regions. Defaults to 1.
2682 <name>hbase.region.replica.storefile.refresh.memstore.multiplier</name>
2685 The multiplier for a “store file refresh” operation for the secondary region replica. If a region server has memory pressure, the secondary region will refresh it’s store files if the memstore size of the biggest secondary replica is bigger this many times than the memstore size of the biggest primary replica. Set this to a very big value to disable this feature (not recommended).
2690 <name>hbase.region.replica.wait.for.primary.flush</name>
2693 Whether to wait for observing a full flush cycle from the primary before start serving data in a secondary. Disabling this might cause the secondary region replicas to go back in time for reads between region movements.
2698 One thing to keep in mind also is that, region replica placement policy is only enforced by the `StochasticLoadBalancer` which is the default balancer.
2699 If you are using a custom load balancer property in hbase-site.xml (`hbase.master.loadbalancer.class`) replicas of regions might end up being hosted in the same server.
2701 ==== Client side properties
2703 Ensure to set the following for all clients (and servers) that will use region replicas.
2708 <name>hbase.ipc.client.specificThreadForWriting</name>
2711 Whether to enable interruption of RPC threads at the client side. This is required for region replicas with fallback RPC’s to secondary regions.
2715 <name>hbase.client.primaryCallTimeout.get</name>
2716 <value>10000</value>
2718 The timeout (in microseconds), before secondary fallback RPC’s are submitted for get requests with Consistency.TIMELINE to the secondary replicas of the regions. Defaults to 10ms. Setting this lower will increase the number of RPC’s, but will lower the p99 latencies.
2722 <name>hbase.client.primaryCallTimeout.multiget</name>
2723 <value>10000</value>
2725 The timeout (in microseconds), before secondary fallback RPC’s are submitted for multi-get requests (Table.get(List<Get>)) with Consistency.TIMELINE to the secondary replicas of the regions. Defaults to 10ms. Setting this lower will increase the number of RPC’s, but will lower the p99 latencies.
2729 <name>hbase.client.replicaCallTimeout.scan</name>
2730 <value>1000000</value>
2732 The timeout (in microseconds), before secondary fallback RPC’s are submitted for scan requests with Consistency.TIMELINE to the secondary replicas of the regions. Defaults to 1 sec. Setting this lower will increase the number of RPC’s, but will lower the p99 latencies.
2736 <name>hbase.meta.replicas.use</name>
2739 Whether to use meta table replicas or not. Default is false.
2744 Note HBase-1.0.x users should use `hbase.ipc.client.allowsInterrupt` rather than `hbase.ipc.client.specificThreadForWriting`.
2748 In the masters user interface, the region replicas of a table are also shown together with the primary regions.
2749 You can notice that the replicas of a region will share the same start and end keys and the same region name prefix.
2750 The only difference would be the appended replica_id (which is encoded as hex), and the region encoded name will be different.
2751 You can also see the replica ids shown explicitly in the UI.
2753 === Creating a table with region replication
2755 Region replication is a per-table property.
2756 All tables have `REGION_REPLICATION = 1` by default, which means that there is only one replica per region.
2757 You can set and change the number of replicas per region of a table by supplying the `REGION_REPLICATION` property in the table descriptor.
2764 create 't1', 'f1', {REGION_REPLICATION => 2}
2768 put 't1', "r#{i}", 'f1:c1', i
2777 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(“test_table”));
2778 htd.setRegionReplication(2);
2780 admin.createTable(htd);
2783 You can also use `setRegionReplication()` and alter table to increase, decrease the region replication for a table.
2786 === Read API and Usage
2790 You can do reads in shell using a the Consistency.TIMELINE semantics as follows
2794 hbase(main):001:0> get 't1','r6', {CONSISTENCY => "TIMELINE"}
2797 You can simulate a region server pausing or becoming unavailable and do a read from the secondary replica:
2801 $ kill -STOP <pid or primary region server>
2803 hbase(main):001:0> get 't1','r6', {CONSISTENCY => "TIMELINE"}
2806 Using scans is also similar
2810 hbase> scan 't1', {CONSISTENCY => 'TIMELINE'}
2815 You can set the consistency for Gets and Scans and do requests as follows.
2819 Get get = new Get(row);
2820 get.setConsistency(Consistency.TIMELINE);
2822 Result result = table.get(get);
2825 You can also pass multiple gets:
2829 Get get1 = new Get(row);
2830 get1.setConsistency(Consistency.TIMELINE);
2832 ArrayList<Get> gets = new ArrayList<Get>();
2835 Result[] results = table.get(gets);
2842 Scan scan = new Scan();
2843 scan.setConsistency(Consistency.TIMELINE);
2845 ResultScanner scanner = table.getScanner(scan);
2848 You can inspect whether the results are coming from primary region or not by calling the `Result.isStale()` method:
2852 Result result = table.get(get);
2853 if (result.isStale()) {
2860 . More information about the design and implementation can be found at the jira issue: link:https://issues.apache.org/jira/browse/HBASE-10070[HBASE-10070]
2861 . HBaseCon 2014 talk: link:https://hbase.apache.org/www.hbasecon.com/#2014-PresentationsRecordings[HBase Read High Availability Using Timeline-Consistent Region Replicas] also contains some details and link:http://www.slideshare.net/enissoz/hbase-high-availability-for-reads-with-time[slides].
2863 ifdef::backend-docbook[]
2866 // Generated automatically by the DocBook toolchain.
2867 endif::backend-docbook[]