This article covers the internal design of Durable Memory. Intended for Ignite developers. The reasoning behind the durable memory is described in the main documentation: https://apacheignite.readme.io/docs/durable-memory
The reasoning behind the durable memory is described in the main documentation: https://apacheignite.readme.io/docs/durable-memory
Let's split the memory into pages (synonyms: buffers, block, chunks). Let's consider the Page as a fundamental unit the whole memory is split into. This makes the memory addressing page-based.
Next, sometimes a query might require an SQL index for execution. The memory has to store not only data entries inside of the pages but builds and maintain indexes as well. If Ignite used a memory mapped files approach, it would be required to read all the data to process the first query. Instead of this, index data is also kept in pages and can store both in RAM on disk if the latter is enabled.
Now let's introduce an integer number that will define an index of Page - idx (4 bytes, unique within cache, partition and in current local node). In continious memory segment page is located at specific offset:
Let's also add partition identifier (2 bytes), and composed indetifier is effectivePageId, see PageIdUtils#effectivePageId
Using this page identifier it's possible to link pages together to build dependencies between them. For instance, this is how we can link 2 pages together by keeping child page ID in the root page:
The ability to link the pages gives a way to organize pages into more complex structures such as trees. Ignite taps into this by using B+Tree for index and data pages arrangements.
If Ignite Persistence is used then after a restart Ignite will load the tree's root node (metadata page) and be able to iterate over the tree layers preloading each new missing page in memory from disk on demand. Also, the tree pages can be merged into one if less of 50% of space within page is used by payload data.
B+Tree are used for SQL indexes: tree maps field value to reference to entry value.
Page content is stored in RAM in segments. Actually memory region allocated in RAM is not continious sequence of pages.
Ignite uses a special component that manages information about pages currently available in memory segment (LoadedPagesTable, ex FullPageIdTable) and ID mapping to region address. There is one page ID table per memory segment chunk (UnsafeChunk, DirectMemoryRegion). For unsafe segment chunk sun.misc.Unsafe is used internally, which provides memory for off-heap data storage.
LoadedPagesTable (PageIdTable) manages mapping from Page ID to relative pointer map (rowAddr) within unsafe segment chunk.
Each segment manages it's own lock. Lock protects segment content (page table) from concurrent modification. By default segment count is determined by available CPUs, but may be configured by DataStorageConfiguration.setConcurrencyLevel().
Splitting each data region (DataRegionConfiguration) to a number of segments allows to minimise contention on one lock for region (striping technique is used).
Structure of segments and Loaded Pages Map is shown at fugure:
Since Ignite version 2.5 Loaded Pages Id Table uses Robin Hood hashing: backward shift deletion algorithm for maintatining HashMap of FullPageId (CacheId, PageId)->(Address, PartGeneration).
To select approrpiate segment Ignite hashes Full Page Id, and (hash % segmentNo) gives the number.
In segment in LoadedPagesTable Ignite also hashes FullPageId to select approptiate bucket in the table.
In case of hash collision inside LoadedPagesTable lineral probe is used to find page by ID. If empty bucket is found, search is finished: page is not present in RAM.
Segment lock is read-write:
Page itself also has its own lock. This lock may be acquired only for page available in RAM and only for pinned (acquired) page.
Since Ignite version 2.5 there are two optimizations introduced. Segment write lock
For read case segment lock is relased, but page write lock is acquired instead, so user thread will wait on page lock instead of segment lock during page is loaded. This decreases contention on segment lock during long running IO operation. Segment lock is hold for short time to acquire page and insert it into table, but released before IO.
In case of flusing dirty page (see section page replacement below) there is additional synchronized map of pages being written to disk, so page read can't be started for such pages until removal from this map. This map is usually not big and most likely page is not there.
This section describes possible pages and entries operations related to rotation with disk or completely removal data from grid.
|Term||Activated||Comments||Configuration||Level of operation||In memory only mode||Persistency mode|
Expiration (aka TTL)
Sets expire time of entry after entry creation/access/update
/ a number of issues exist
Region is full
Completely removes entry from grid. Reasonable with 3rd party persistence
Entry (+ page is used to find more entries to remove)
On Heap eviction
Depends on policy
Near caches and On-Heap caches (1.x)
only for near /on-heap caches
Region is full
Not configurable by user
If durable memory operates with disk (native peristence is covered in Ignite Persistent Store - under the hood), paging is handled automatically by Ignite.
PageIdTable (FullPageIdTable) table is used to check
As a result, even SQL queries can be fully utilized from Ignite applications when only a subset of pages is in memory. In this case required pages will be taken from disk during query execution.
If memory amount is less than whole size of B+tree for SQL index, Ignite still can operate. When Ignite runs out of RAM memory for the new pages allocation, some of the pages will be purged from RAM (as it can be loaded from disk later).
This process is named page rotation (page replacement, swap to disk, historical naming - page eviction).
Let's suppose RAM memory is fully filled with pages, and it is required to allocate new. It is required to evict some page from memory.
Example of rotation of new page and clear page in RAM is shown in picture.
Simplest algorithm would be selected selecting page to rotate is LRU, but it requires double linked list. It is not simple to implement such structure in off heap.
Algorithm used instead is Random-LRU (most recent access timestamp is stored for a page). This algorihtm is used always if Persistent Data store mode enabled. Ignite will adaptively page-in and page-out memory to disk in a fashion very similar to how modern operating systems handle virtual memory.
Replacement (rotation) of pages is started only if memory segment is full and it is impossible to allocate page in segment chunk.
During first page rotated warning message is printed to logs
Message for versions early than 2.5 was:
If this message appeared in log it means segment is full and for allocation of new page it is required to purge some other page.
Page replacement may have negative influence to performance because in some cases it is possible that Ignite continiously evicts page from RAM and some steps later reqiures this page data. In this case it is required to re-read data from disc.
If Native Peristence is not used, then upcoming hit to memory limit requires Ignite to clean up some data (otherwise IgniteOutOfMemory may occur). In this case, users have to decide how to deal with out-of-memory situations by specifying their own eviction policy. Ignite will not magically page to disk and so users need to configure eviction.
Ignite uses Eviction Policy to determine which page to select to be evicted. Policy is configured by user. This configuration is useful if Ignite is used as fast access cache with 3rd party DB as persistence (such as write-behind to an RDBMS).
If eviction is configured we need to remove one cache entry, but removing entry from the middle of page will cause pages fragmentation.
Instead of this we can evict old random page, read all entries and remove all entries one-by-one.
There is only one exception: entry may be currently locked under transaction. In this case such page is excluded from eviction.
This method allows to clean up big continuous segment of memory (usually whole page)
Eviction policy only makes sense when native persistence is disabled because what it does is actually freeing up memory when a user hits the memory limit.
The only way to do this is to destroy inserted data because there is no other way to free memory.
Eviction mechanism, it is both per-page and per-entry:
If there are no concurrent updates, the page becomes empty and will be reused for other user data.
There is second option for eviction if Persitent Data store is not enabled. In that algorithm two most recent access timestamps are stored for every data page.
In case of touch page: Oldest timestamp is overwritten with current time.
In case of eviction: Oldest timestamp is used for eviction decision.
This policy solves case of one-time access of data, for example, one full scan query. Pages touched during running this query is not considered hot. See also documentation
Ignite manages free lists to solve issue with fragmentation in pages (not full pages).
Cache entry [Key, Value] pairs have different size and after placing first entry, pages will have different free sizes
Free list - list of pages, structured by amount of space remained within page.
During selection of page to store new value pair Ignite does the following:
If object is longer than page size, it will require several pages to store
Object is saved from end to beginning.
This allows Ignite to touch page only once. For each new page we already know link to previosly allocated. This allows to reduce number of locks on pages.
For object part which is less than page size, we can use partially filled page from free list.
Let's consider object field update. If marshaller reported that updated field requires same size optimization may be used. Such update does not require page structure change or memory movement.
Page has dirty flag. If value stored in page was changed, but not yet flushed to disk, page is marked as dirty.
In previous case (updated field value has same length) only one page will be marked as dirty.
There is class PageIO - it is abstract class for reading and writing pages. Several implementations also exist: BplusIO, DataPageIO
Every page contain Page header. Page header includes
Data page has its own header in addition to general page. It contains:
After page header page contains items.
Item - internal reference (offset) to payload within page. Item is 2 bytes in length.
See page structure at picture below:
Values are inserted into data page from the end to beginning. Items are filled from beginning to end.
To address particular Key-Value pair ignite uses Link = Page ID + order in page.
Link allows to read K,V pair as N-th item in page.
Deletion of lastest added item is trivial. We can just remove Item, and Key-Value pair without any additional changes (see It3, K,V3 at picture).
More complex algorithm is activated for case of deletion of item from middle of page.
In that case
In the same we need keep external Link to K,V3 pair consistent (Page ID + order=3). This link may be referenced outside, for example, by B+Tree.
This techique brings advantage: at inserting new K,V pair we don’t need to iterate over page to find free space. We can insert after latest item instead.
During deletion of indirect items there is another algorithm is activated.
Page free size is tracked at corresponsing field, regardless to fragmentation occurred. Compaction may be required if insert is not possible. Compaction will change all K,V pairs offsets within page. Defragmentation is performed in values area, references to values are kept unmodified to achieve consistency in B-tree.
To transform Page ID into Link it is possible to write offset to highest bits of Page ID.
Example of re-insertion new K,V4 element after some other K,V2 deleted. Following picture shows Indirect Item to direct Item replacement
B+Tree structure is build mostly the same as binary tree. If requied value was not found, it is compared with some value in the tree. Greater values can be found using rigth link, less - using left.
Binary search is used to find required K. It is required to touch log N of data pages to complete search of value.
Link in B+ Tree allows to read K,V pair or K only depending to object size. There is optimisation done to avoid odd page reads: If indexed value requires less bytes than some threshold, value is written into tree.
Duplicate keys is not possible in B+ Tree.
Hash Index is also B+ Tree (not hash table), key is hashcode and value is link.
DataRegionConfiguration (historical naming is Memory Policy) is especially important when Ignite Persistent Store configuration is enabled.
Several caches in previous Ignite version may allocate uncontrolled amount of memory. In case of limited resources first cache which perfomed allocations wins. There was no way to limit this memory for particular cache.
In 2.0 Ignite version it is possible to control it using DataRegionConfiguration (before 2.3 was named Memory Policy). One data region may include several caches (relation is 1.to.N).
All data may be separated by user to following classes: archive data and operational data:
User now can specify how much memory it is possible to allocate for cache group.
Reference tables (dictionaries) are usually small, and may be assigned to be allocated to memory always.
Following paragraph summarizes results of memory structure changes
For previous Ignite versions - caches were on heap by default. Offheap caches were required configuration, and a number of small regions were allocated for each usage.
Quite long GC pause can look totally the same as failed node from the remote node's point of view.
More heap size used for data causes longer GC Pause. Long GC causes cluster failure bacames more probable.
For 2.1+ Ignite versions: Page memory is used for all data. Caches are placed in off-heap memory. These pages can now be saved and loaded from disk (transparently to user).
Ignite node with persistent store enabled may now start to operate without reading all pages data from disk.