RonDB, automatic thread configuration
This blog introduces how RonDB handles automatic thread configuration. This blog is more technical and dives deeper under the surface of how RonDB operates. RonDB provides a configuration option, ThreadConfig, whereby the user can have full control over the assignment of threads to CPUs, how the CPU locking is to be performed and how the thread should be scheduled.However for the absolute majority of users this is too advanced, thus the managed version of RonDB ensures that this thread configuration is based on best practices found over decades of testing. This means that every user of the managed version of RonDB will get access to a thread configuration that is optimised for their particular VM size.In addition RonDB makes use of adaptive CPU spinning in a way that limits the power usage, but still provides very low latency in all database operations. This improves latency by up to 50% and in most cases more than 10% improvement.RonDB 21.04 uses automatic thread configuration by default. This means that as a user you don’t have to care about the configuration of threads. What RonDB does is that it retrieves the number of CPUs available to the RonDB data node process. In the managed version of RonDB, this is the full VM or bare metal server available to the data node. In the open source version of RonDB one can also limit the amount of CPUs available to RonDB data nodes process by using taskset or numactl when starting the data node. RonDB retrieves information about CPU cores, CPU sockets and connections to the L3 caches of the CPUs. All of this information is used to set up the optimal thread configuration.Thread types in RonDBLDM threads that house the data, query threads that handles read committed queries, tc threads that handles transaction coordination, receive threads that handles receive of network messages, send threads that handles sending of network messages, and main threads that handle metadata operations, asynchronous replication and a number of other things.LDM threadsLDM thread is a key thread type. The LDM thread is responsible to read and write data. It manages the hash indexes, the ordered indexes, the actual data and a set of triggers performing actions for indexes, foreign keys, full replication, asynchronous replication. This thread type is where most of the CPU processing is done. RonDB has an extremely high number of instructions per cycle compared to any other DBMS engine. The LDM thread often executes 1.25 instructions per cycle where many other DBMS engines have reported numbers around 0.25 instructions per cycle. This is a key reason why RonDB has such a great performance both in terms of throughput and latency. This is the result of a design of data structures in RonDB that is CPU cache aware and the functional separation of thread types.Query threadsQuery thread is a new addition that was introduced in NDB Cluster 8.0.23. In NDB this is not used by default, RonDB enables the use of query threads by default in the automatic thread configuration. The query threads run the same code as the LDM threads and handles a subset of the operations that the LDM can handle. A normal SELECT query will use read committed queries that can be executed by the query threads. A table partition (sometimes referred to as a table fragment or shard) belongs to a certain LDM thread, thus only this LDM thread can be used for writes and locked reads on rows in this table partition. However for read committed queries, the query threads can be used.To achieve the best performance RonDB uses CPU locking. In Linux, it is quite common that a thread migrates from one CPU to another CPU. If the thread migrates to a CPU belonging to a different CPU core, the thread will suffer a lot of CPU cache misses immediately after being migrated. To avoid this RonDB lock thread to a certain CPU core. Thus it is possible to migrate the thread, but only to the other CPU in the CPU core that share the same CPU caches.Query threads and LDM threads are organised into Round Robin groups. Each Round Robin group consists of between 4 and 8 LDM threads and the same amount of query threads. All threads within one Round Robin group share the same CPU L3 cache. This ensures that we retain the CPU efficiency even with the introduction of these new query threads. This is important since query threads introduce new mutexes and the performance of these are greatly improved when threads sharing mutexes also share CPU caches. The query thread chosen to execute a query must be in the same Round Robin group as the data owning LDM thread is.Query thread makes it possible to decrease the amount of partitions in a table. As an example we are able to process more than 3 times as many transactions per second using a single partition in Sysbench OLTP RW compared to when we only use LDM threads.Most key-value stores have data divided into table partitions for the primary key of the table. Many key-value stores also contain additional indexes on columns that are not used for partitioning. Since the table is partitioned, this means that each table partition will contain each of those additional indexes.When performing a range scan on such an index, each table partition must be scanned. Thus the cost of performing range scans increases as the number of table partitions increases. RonDB can scale the reads in a single partition to many query threads, this makes it possible to decrease the number of table partitions in RonDB. In Sysbench OLTP RW this improves performance by around 20% even in a fairly small 2-node setup of RonDB.In addition query threads ensure that hotspots in the tables can be handled by many threads, thus avoiding the need to partition even more to handle hotspots.At the same time a modest amount of table partitions increases the amount of writes that we can perform on a table and it makes it possible to parallelise range scans which will speed up complex query execution significantly. Thus in RonDB we have attempted to find a balance between overhead and improved parallelism and improved write scalability.Costs of key lookups are not greatly affected by the number of partitions since those use a hash lookup and thus always go directly to the thread that can execute the key lookup.RonDB locks LDM threads and query threads in pairs. There is one LDM thread and one query thread in each such LDM group, we attempt to lock this LDM Group to one CPU core. LDM Groups are organised into Round Robin Groups. A common choice for a scheduling algorithm in an architecture like this would be to use a simple round robin scheduler. However such an algorithm is too simple for this model. We have two problems to overcome. The first is that the load on LDM threads is not balanced since we have decreased the number of table partitions in a table. Second writes and locked reads can only be scheduled in an LDM thread. Thus it is important to use the Read Committed queries to achieve a balanced load.Given that we use less table partitions in RonDB compared to other solutions, there is arisk of imbalanced load on the CPUs. This problem is solved by two things. First weuse a two-level load balancer on LDM and Query threads. This ensures that we willmove away work from overloaded LDM threads towards unused query threads.Second since the LDM and Query threads share the same CPU core we will make greatprogress in query threads that execute on the same CPU core as an LDM thread that iscurrently underutilized. Thus we expect that this architecture will achieve a balanced loadon the CPU cores in the data node architecture.LDM and query threads use around 50-60% of the available CPU resources in a data node.tc threadsThe tc threads receive all database operations sent from the NDB API. It takes care ofcoordinating transactions and decides which node should take care of the queries.It uses around 20-25% of the CPU resources. The NDB API selects tc threads in a nodeusing a simple round robin scheme.receive threadsThe receive threads take care of a subset of the communication links. Thus the receivethread load is usually fairly balanced but can be a bit more unbalanced if certain API nodesare more used in querying RonDB. The communication links between data nodes in thesame node group are heavily used when performing updates. To ensure that RonDB canscale in this situation these node links use multiple communication links. Receive threadsuse around 10-15% of the CPU resources.send threadsThe send threads assist in sending networking messages to other nodes. The sending ofmessages can be done by any thread and there is an adaptive algorithm that assigns moreload for sending to threads that are not so busy. The send threads assists in sending toensure that we have enough capacity to handle all the load. It is not necessary to havesend threads, the threads can handle sending even without a send thread. Send threadsuse around 0-10% of the CPUs available.The total cost of sending can be quite substantial in a distributed database engine, thusthe adaptive algorithm is import to balance out this load on the various threads inthe data node.main threadsThe main threads can be 0, 1 or 2. These threads handle a lot of the interactions aroundcreating tables, indexes and any other metadata operation. They also handle a lot of thecode around recovery and heartbeats. They are handling any subscriptions toasynchronous replication events used by replication channels to other RonDB clusters.Comparison of RonDB thread modelBackgroundRonDB is based on NDB Cluster. NDB was focused on being a high-availability key-valuestore from its origin in database research in the 1990s. The thread model in NDB isinherited from a telecom system developed in Ericsson called AXE. Interestingly in one ofmy first jobs at Philips I worked on a banking system developed in the 1970s, this systemhad a very similar model compared to the original thread model in NDB and in AXE. In theoperating system development time-sharing has been the dominant model since a long timeback. However the model used in NDB where the execution thread is programmed as anasynchronous engine where the application handles a state machine has a hugeperformance advantage when handling many very small tasks. A normal task in RonDBis a key lookup, or a small range scan. Each of those small tasks is actually divided evenfurther when performing updates and parallel range scans.This means that the length of a task in RonDB is on the order of 500 ns up to around10 microseconds.Traditional thread design for key-value storesTime-sharing operating systems are not designed to handle context switches of thismagnitude. NDB was designed with this understanding from the very beginning. Earlycompetitors of NDB used normal operating system threads for each transactionand even in a real-time operating system this had no chance to compete with theeffectiveness of NDB. None of these competitors are still around competing in thekey-value store market.Asynchronous thread modelThe first thread model in NDB used a single thread to handle everything, send, receive,database handling and transaction handling. This is version 1 of the thread architecture,this is implemented also in the open source version of Redis. With the development ofmulti-core CPUs it became obvious that more threads were needed. What NDB didhere was introduce both a functional separation of threads and partitioning the data toachieve a more multi-threaded execution environment. This is version 2 of the threadarchitecture.Modern competitors of RonDB have now understood the need to use asynchronousprogramming to achieve the required performance in a key-value store. We see this inAeroSpike, Redis, ScyllaDB and many other key-value stores. Thus the industry hasfollowed the RonDB road to achieving an efficient key-value store implementation.Functional separation of threadsMost competitors have opted for only partitioning the data and thus each thread stillhas to execute all the code for meta data handling, replication handling, send, receive anddatabase operations. Thus RonDB has actually advanced version 2 of the threadarchitecture further than its competitors.One might ask, what difference does this make?All modern CPUs use both a data cache and an instruction cache. By combining allfunctions inside one thread, the instruction cache will have to execute more code.In RonDB the LDM thread only executes the operation to change the data structures,the tc thread only executes code to handle transactions and the receive thread canfocus on the code to execute network receive operations. This makes each thread moreefficient. The same is true for the CPU data cache, the LDM thread need not bother withthe data structures used for transaction handling and network receive. It can focus theCPU caches on the requirements for database operations which is challenging enoughin a database engine.A scalable key-value store designA simple splitting of data into different table partitions makes sense if all operationstowards the key-value store are primary key lookups or unique key lookups. Howevermost key-value stores also require performing general search operations as part of theapplication. These search operations are implemented as range scans with searchconditions, these scale not so well with a simple splitting of data.To handle this RonDB introduces version 3 of the thread architecture that uses acompromise where we still split the data, but we introduce query threads to assist theLDM threads in reading the data. Thus RonDB can handle hotspots of data and requirefewer number of table partitions to achieve the required scalability of the key-value store.Thoughts on a v4 of the thread architecture has already emerged, so expect thisdevelopment to continue for a while more. This includes even better handling ofthe higher latency to persistent memory data structures.Finally, even if a competitor managed to replicate all of those features of RonDB,RonDB has another ace in the 3-level distributed hashing algorithm that makes use ofa CPU cache aware data structure.ConclusionAll of those things combined makes us comfortable that RonDB will continue to leadthe key-value store market in terms of lowest Latency, highest Availability, thehighest Throughput and the most Scalable data storage. Thus, beingthe best LATS database in the industry.