Tuesday, October 12, 2021

Log Structured Merge Trees(LSM) 原理 | 20 minutes to warmup

Oct. 12, 2021

Here are my notes:

  1. LSM vs B+ vs ISAM, learn more about three data structure
  2.  LSM是当前被用在许多产品的文件结构策略:HBase, Cassandra, LevelDB, SQLite, 甚至在mangodb3.0中也带了一个可选的LSM引擎(Wired Tiger 实现的)。
  3. Understand SSTable, Memtable, Compaction,Bloom filter

Log Structured Merge Trees(LSM) 原理

十年前,谷歌发表了 “BigTable” 的论文,论文中很多很酷的方面之一就是它所使用的文件组织方式,这个方法更一般的名字叫 Log Structured-Merge Tree。

LSM是当前被用在许多产品的文件结构策略:HBase, Cassandra, LevelDB, SQLite, 甚至在mangodb3.0中也带了一个可选的LSM引擎(Wired Tiger 实现的)。

LSM 有趣的地方是他抛弃了大多数数据库所使用的传统文件组织方法,实际上,当你第一次看它是违反直觉的。

背景知识

简单的说,LSM被设计来提供比传统的B+树或者ISAM更好的写操作吞吐量,通过消去随机的本地更新操作来达到这个目标。

那么为什么这是一个好的方法呢?这个问题的本质还是磁盘随机操作慢,顺序读写快的老问题。这二种操作存在巨大的差距,无论是磁盘还是SSD。

上图很好的说明了这一点,他们展现了一些反直觉的事实,顺序读写磁盘(不管是SATA还是SSD)快于随机读写主存,而且快至少三个数量级。这说明我们要避免随机读写,最好设计成顺序读写。

所以,让我们想想,如果我们对写操作的吞吐量敏感,我们最好怎么做?一个好的办法是简单的将数据添加到文件。这个策略经常被使用在日志或者堆文件,因为他们是完全顺序的,所以可以提供非常好的写操作性能,大约等于磁盘的理论速度,也就是200~300 MB/s。

因为简单和高效,基于日志的策略在大数据之间越来越流行,同时他们也有一些缺点,从日志文件中读一些数据将会比写操作需要更多的时间,需要倒序扫描,直接找到所需的内容。

这说明日志仅仅适用于一些简单的场景:1. 数据是被整体访问,像大部分数据库的WAL(write-ahead log) 2. 知道明确的offset,比如在Kafka中。

所以,我们需要更多的日志来为更复杂的读场景(比如按key或者range)提供高效的性能,这儿有4个方法可以完成这个,它们分别是:

1.   二分查找: 将文件数据有序保存,使用二分查找来完成特定key的查找。

2.   哈希:用哈希将数据分割为不同的bucket

3.   B+树:使用B+树 或者 ISAM 等方法,可以减少外部文件的读取

4.   外部文件: 将数据保存为日志,并创建一个hash或者查找树映射相应的文件。

所有的方法都可以有效的提高了读操作的性能(最少提供了O(log(n)) ),但是,却丢失了日志文件超好的写性能。上面这些方法,都强加了总体的结构信息在数据上,数据被按照特定的方式放置,所以可以很快的找到特定的数据,但是却对写操作不友善,让写操作性能下降。

更糟糕的是,当我们需要更新hash或者B+树的结构时,需要同时更新文件系统中特定的部分,这就是上面说的比较慢的随机读写操作。这种随机的操作要尽量减少。

所以这就是 LSM 被发明的原理, LSM 使用一种不同于上述四种的方法,保持了日志文件写性能,以及微小的读操作性能损失。本质上就是让所有的操作顺序化,而不是像散弹枪一样随机读写。

很多树结构可以不用 update-in-place,最流行就是

append-only Btree  http://www.bzero.se/ldapd/btree.html

也称为 Copy-On-Write Tree。他们通过顺序的在文件末尾重复写对结构来实现写操作,之前的树结构的相关部分,包括最顶层结点都会变成孤结点。尽管通过这种方法避免了本地更新,但是因为每个写操作都要重写树结构,放大了写操作,降低了写性能。

The Base LSM Algorithm

从概念上说,最基本的LSM是很简单的 。将之前使用一个大的查找结构(造成随机读写,影响写性能),变换为将写操作顺序的保存到一些相似的有序文件(也就是sstable)中。所以每个文件包含短时间内的一些改动。因为文件是有序的,所以之后查找也会很快。文件是不可修改的,他们永远不会被更新,新的更新操作只会写到新的文件中。读操作检查很多的文件。通过周期性的合并这些文件来减少文件个数。 

让我们更具体的看看,当一些更新操作到达时,他们会被写到内存缓存(也就是memtable)中,memtable使用树结构来保持key的有序,在大部 分的实现中,memtable会通过写WAL的方式备份到磁盘,用来恢复数据,防止数据丢失。当memtable数据达到一定规模时会被刷新到磁盘上的一个新文件,重要的是系统只做了顺序磁盘读写,因为没有文件被编辑,新的内容或者修改只用简单的生成新的文件。

所以越多的数据存储到系统中,就会有越多的不可修改的,顺序的sstable文件被创建,它们代表了小的,按时间顺序的修改。

因为比较旧的文件不会被更新,重复的纪录只会通过创建新的纪录来覆盖,这也就产生了一些冗余的数据。

所以系统会周期的执行合并操作(compaction)。 合并操作选择一些文件,并把他们合并到一起,移除重复的更新或者删除纪录,同时也会删除上述的冗余。更重要的是,通过减少文件个数的增长,保证读操作的性能。因为sstable文件都是有序结构的,所以合并操作也是非常高效的。

当一个读操作请求时,系统首先检查内存数据(memtable),如果没有找到这个key,就会逆序的一个一个检查sstable文件,直到key被找到。因为每个sstable都是有序的,所以查找比较高效(O(logN)),但是读操作会变的越来越慢随着sstable的个数增加,因为每一个 sstable都要被检查。(O(K log N), K为sstable个数, N 为sstable平均大小)。

所以,读操作比其它本地更新的结构慢,幸运的是,有一些技巧可以提高性能。最基本的的方法就是页缓存(也就是leveldb的 TableCache,将sstable按照LRU缓存在内存中)在内存中,减少二分查找的消耗。LevelDB 和 BigTable 是将 block-index 保存在文件尾部,这样查找就只要一次IO操作,如果block-index在内存中。一些其它的系统则实现了更复杂的索引方法。

即使有每个文件的索引,随着文件个数增多,读操作仍然很慢。通过周期的合并文件,来保持文件的个数,因些读操作的性能在可接收的范围内。即便有了合并操作,读操作仍然会访问大量的文件,大部分的实现通过布隆过滤器来避免大量的读文件操作,布隆过滤器是一种高效的方法来判断一个sstable中是否包含一个特定的key。(如果bloom说一个key不存在,就一定不存在,而当bloom说一个文件存在是,可能是不存在的,只是通过概率来保证)所有的写操作都被分批处理,只写到顺序块上。另外,合并操作的周期操作会对IO有影响,读操作有可能会访问大量的文件(散乱的读)。这简化了算法工 作的方法,我们交换了读和写的随机IO。这种折衷很有意义,我们可以通过软件实现的技巧像布隆过滤器或者硬件(大文件cache)来优化读性能。

 

Basic Compaction

为了保持LSM的读操作相对较快,维护并减少sstable文件的个数是很重要的,所以让我们更深入的看一下合并操作。这个过程有一点儿像一般垃圾回收算法。

当一定数量的sstable文件被创建,例如有5个sstable,每一个有10行,他们被合并为一个50行的文件(或者更少的行数)。这个过程一 直持续着,当更多的有10行的sstable文件被创建,当产生5个文件时,它们就被合并到50行的文件。最终会有5个50行的文件,这时会将这5个50 行的文件合并成一个250行的文件。这个过程不停的创建更大的文件。

 

上述的方案有一个问题,就是大量的文件被创建,在最坏的情况下,所有的文件都要搜索。

Levelled Compaction

更新的实现,像 LevelDB 和 Cassandra解决这个问题的方法是:实现了一个分层的,而不是根据文件大小来执行合并操作。这个方法可以减少在最坏情况下需要检索的文件个数,同时也减少了一次合并操作的影响。

按层合并的策略相对于上述的按文件大小合并的策略有二个关键的不同:

1.   每一层可以维护指定的文件个数,同时保证不让key重叠。也就是说把key分区到不同的文件。

2.   因此在一层查找一个key,只用查找一个文件。第一层是特殊情况,不满足上述条件,key可以分布在多个文件中。

3.   每次,文件只会被合并到上一层的一个文件。当一层的文件数满足特定个数时,一个文件会被选出并合并到上一层。这明显不同与另一种合并方式:一些相近大小的文件被合并为一个大文件。

这些改变表明按层合并的策略减小了合并操作的影响,同时减少了空间需求。除此之外,它也有更好的读性能。但是对于大多数场景,总体的IO次数变的更多,一些更简单的写场景不适用。

总结

所以, LSM 是日志和传统的单文件索引(B+ tree, Hash Index)的中立,他提供一个机制来管理更小的独立的索引文件(sstable)。

通过管理一组索引文件而不是单一的索引文件,LSM 将B+树等结构昂贵的随机IO变的更快,而代价就是读操作要处理大量的索引文件(sstable)而不是一个,另外还是一些IO被合并操作消耗。

如果还有不明白的,这还有一些其它的好的介绍。

关于 LSM 的一些思考

为什么 LSM 会比传统单个树结构有更好的性能?

我们看到LSM有更好的写性能,同时LSM还有其它一些好处。 sstable文件是不可修改的,这让对他们的锁操作非常简单。一般来说,唯一的竞争资源就是memtable,相对来说需要相对复杂的锁机制来管理在不同的级别。

所以最后的问题很可能是以写为导向的压力预期如何。如果你对LSM带来的写性能的提高很敏感,这将会很重要。大型互联网企业似乎很看中这个问题。 Yahoo 提出因为事件日志的增加和手机数据的增加,工作场景为从 read-heavy 到 read-write。许多传统数据库产品似乎更青睐读优化文件结构。

因为可用的内存的增加,通过操作系统提供的大文件缓存,读操作自然会被优化。写性能(内存不可提高)因此变成了主要的关注点,所以采取其它的方法,硬件提升为读性能做的更多,相对于写来说。因此选择一个写优化的文件结构很有意义。

理所当然的,LSM的实现,像LevelDB和Cassandra提供了更好的写性能,相对于单树结构的策略。



作者:wuxinliulei
链接:https://www.zhihu.com/question/19887265/answer/78839142
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

 


Log-structured merge-tree | Wiki article | 20 minutes to warmup

 In computer science, the log-structured merge-tree (or LSM tree) is a data structure with performance characteristics that make it attractive for providing indexed access to files with high insert volume, such as transactional log data. LSM trees, like other search trees, maintain key-value pairs. LSM trees maintain data in two or more separate structures, each of which is optimized for its respective underlying storage medium; data is synchronized between the two structures efficiently, in batches.

One simple version of the LSM tree is a two-level LSM tree.[1] As described by Patrick O'Neil, a two-level LSM tree comprises two tree-like structures, called C0 and C1. C0 is smaller and entirely resident in memory, whereas C1 is resident on disk. New records are inserted into the memory-resident C0 component. If the insertion causes the C0 component to exceed a certain size threshold, a contiguous segment of entries is removed from C0 and merged into C1 on disk. The performance characteristics of LSM trees stem from the fact that each component is tuned to the characteristics of its underlying storage medium, and that data is efficiently migrated across media in rolling batches, using an algorithm reminiscent of merge sort.


Most LSM trees used in practice employ multiple levels. Level 0 is kept in main memory, and might be represented using a tree. The on-disk data is organized into sorted runs of data. Each run contains data sorted by the index key. A run can be represented on disk as a single file, or alternatively as a collection of files with non-overlapping key ranges. To perform a query on a particular key to get its associated value, one must search in the Level 0 tree and also each run.

A particular key may appear in several runs, and what that means for a query depends on the application. Some applications simply want the newest key-value pair with a given key. Some applications must combine the values in some way to get the proper aggregate value to return. For example, in Apache Cassandra, each value represents a row in a database, and different versions of the row may have different sets of columns.[2]


In order to keep down the cost of queries, the system must avoid a situation where there are too many runs.

Extensions to the 'leveled' method to incorporate B+ tree structures have been suggested, for example bLSM[3] and Diff-Index.[4]

LSM trees are used in data stores such as Apache AsterixDB, Bigtable, HBase, LevelDB, SQLite4,[5] Tarantool,[6] RocksDB, WiredTiger,[7] Apache Cassandra, InfluxDB[8] and ScyllaDB.

References[edit]

  1. ^ O'Neil 1996, p. 4
  2. ^ "Leveled Compaction in Apache Cassandra : DataStax". February 13, 2014. Archived from the original on February 13, 2014.
  3. ^ https://web.archive.org/web/20160127170015/http://www.eecs.harvard.edu/~margo/cs165/papers/gp-lsm.pdf
  4. ^ http://researcher.ibm.com/researcher/files/us-wtan/DiffIndex-EDBT14-CR.pdf
  5. ^ "SQLite4 with LSM Wiki". SQLite.
  6. ^ "An application server together with a database manager". Retrieved April 3, 2018. Tarantool’s disk-based storage engine is a fusion of ideas from modern filesystems, log-structured merge trees and classical B-trees.
  7. ^ "GitHub - wiredtiger/wiredtiger: WiredTiger's source tree". December 4, 2019 – via GitHub.
  8. ^ Dix, Paul (October 7, 2015). "[New] InfluxDB Storage Engine | Time Structured Merge Tree".
General

External links[edit]

Crude oil price: RIG stock | Above $80

 

U.S. Crude Closes Above $80 With Energy Crisis Boosting Demand



·3 min read

(Bloomberg) -- West Texas Intermediate crude closed above $80 a barrel for the first time since late 2014 as a growing power crisis from Europe to Asia boosts demand for oil ahead of winter.

U.S. crude futures advanced 1.5% on Monday in New York, while its global counterpart Brent rose closer to the $85-a-barrel mark. Prices of coal and natural gas have surged globally with stockpiles running low before the Northern Hemisphere winter, prompting some switching to oil products such as diesel and fuel oil.

It is quickly tightening the market as the Organization of Petroleum Exporting Countries and its allies are sticking with their plan to only gradually roll back production cuts. The oil market’s price structure is flashing bullishness, with the difference between New York crude’s front two contracts hit the widest in more than two years, indicating shrinking supplies in the U.S. storage hub of Cushing, Oklahoma.

“There is definitely this fear of the supply side going to dry up,” said Fiona Cincotta, senior financial markets analyst at City Index. Even OPEC adding back supply to the market is not “necessarily going to have a massive impact on cooling the price of oil. Oil to $90 is clearly in sight.”

Crude futures have advanced about 20% since mid-August as the energy crisis has intensified. Saudi Aramco estimates the gas shortage has already increased oil demand by around 500,000 barrels a day, while Citigroup estimates it could reach about 1 million a day in a bullish case.

Citi raised its Brent price estimate for this quarter to $85 a barrel, potentially increasing to as high as $90 at times, on “higher demand, lost supply, gas-to-oil switching and price contagion this winter,” according to a report.

See also: In a World Fighting Climate Change, Fossil Fuels Take Revenge

If prices continue to rise, the U.S. is likely to ask OPEC member states to pump more crude to help ease a surge the energy prices, said Daniel Yergin, vice chairman of IHS Markit, in a Bloomberg Television interview. Over the past few months, the White House has been in communication with OPEC, pushing them to boost their output while stressing the importance of affordable energy.

Various underlying oil market gauges are showing signs of strength. WTI crude’s nearest contract traded at the biggest premium to second-month futures since September 2019 on Monday, in a sign of tighter supplies. The so-called prompt spread has increased as more of the world attempts to substitute fuel oil for natural gas as quickly as possible.

A favored oil trade of the world’s hedge funds, WTI crude’s so-called Dec.-Red-Dec. spread, also strengthened. The spread topped $8 a barrel and is at the strongest on a rolling basis since 2014.

While crude markets still have room to grow as supply runs short and demand increases, it won’t last forever. Oil prices will eventually hit a ceiling as the “pain threshold, or the moment when the expensive price of oil will significantly impact demand and the global economic recovery, according to Pavel Molchanov, an analyst at Raymond James & Associates Inc.

“The ceiling on price will be a combination of OPEC’s response and the threshold of pain in relation to demand,” he said.


Sunday, October 10, 2021

Eric Nuttall - Oil & Energy Market Update - July 2021

Oct. 10, 2021

Here is the link.

 The Oil Party Has Just Begun.

Join Eric Nuttall, Senior Portfolio Manager at Ninepoint Partners as he outlines why the multi-year oil bull market should be much less volatile than in years past, and what that means for energy stocks in the next year. Eric Nuttall is a Partner and Senior Portfolio Manager with Ninepoint Partners LP. He joined the firm in August 2017 and was previously a Portfolio Manager at Sprott Asset Management LP since February 2003. Eric's views are frequently sought after by the Business News Network (BNN), The Globe and Mail, the National Post, the Calgary Herald, CNBC, and the Wall Street Journal. Eric graduated with High Honours from Carleton University with an Honours Bachelor of International Business.


Eric Nuttall - Oil & Energy Market Update - July 2021

Oct. 10, 2021

Here is the link. 

The Oil Party Has Just Begun. Join Eric Nuttall, Senior Portfolio Manager at Ninepoint Partners as he outlines why the multi-year oil bull market should be much less volatile than in years past, and what that means for energy stocks in the next year. Eric Nuttall is a Partner and Senior Portfolio Manager with Ninepoint Partners LP. He joined the firm in August 2017 and was previously a Portfolio Manager at Sprott Asset Management LP since February 2003. Eric's views are frequently sought after by the Business News Network (BNN), The Globe and Mail, the National Post, the Calgary Herald, CNBC, and the Wall Street Journal. Eric graduated with High Honours from Carleton University with an Honours Bachelor of International Business.


Oil could continue to climb to $100 per barrel: Stephen Schork

Oct. 10, 2021

Here is the link. 

#oilprices #gasprices #crudeoil Stephen Schork The Schork Group Principal joins the Yahoo Finance Live panel with the latest on the oil markets. Don't Miss: Valley of Hype: The Culture That Built Elizabeth Holmes WATCH HERE: https://youtu.be/Sb179GLPNYE

ConocoPhillips CEO Sees Pre-Covid Oil Demand Returning in Months

Oct. 10, 2021

Here is the link. 

Sep.21 -- Ryan Lance, ConocoPhillips Chairman and CEO, discusses bullishness over the next couple of years. He speaks on “Bloomberg Markets, The European Close.”