在大型服务中,内存或磁盘等硬件故障时有发生。一旦某个节点发生故障,该节点上承载的所有复制组就会降至两份副本。修复存储副本的过程可能需要数分钟,因为此过程不仅要复制 B 树结构,还要复制预写日志。为快速恢复,当领导副本检测到某个存储副本不健康时,它会立即添加一个日志副本,以确保持久性不受影响。添加日志副本只需几秒钟,因为系统只需从健康副本拷贝最近的预写日志,而无需复制 B 树结构。通过这种仅复制日志的快速修复方式,DynamoDB 能够在绝大多数情况下,保证最近写入操作的高持久性和系统的持续可用性。
如果某个 Region 宕机,全局表继续在其他 Region 上读写,不受影响。宕机区域恢复后,会自动同步补全所有挂起写入数据,无需人工干预。
假设有两个区域 A 和 B,那么两者的服务都可用时的流程如下:
客户端(App A)向 Region A 的 DynamoDB 表写入数据,写操作一旦在 Region A 达到持久化,立即返回成功给 App A,保证写入延迟最低(最终一致性或强一致性均可选)。DynamoDB 利用 Global Tables 机制,通过内部的 DynamoDB Streams 将写操作异步推送到 Region B 的副本表,在平时可让 Region B 的应用(App B)直接从 Region A 读取最新数据。副本表会在通常 1 秒内同步到最新写入项,Get 操作返回数据给 App B。
如果完成上图的第五步之后,Region A 的数据存储宕机,那么 DynamoDB 基于全局表的故障回复和切换如下:
通过 DNS 或客户端配置,将写流量切换到 Region B。切换后,App B 向 Region B 写入新数据,Region B 本地确认写入成功。当 Region A 恢复后,全局表会将 Region B 的变更异步推回 Region A。
复制
Region 内复制
多个可用区(AZ1、AZ2、AZ3)通过高速专有网络互联,数据同步延迟通常在毫秒级。每个 AZ 内都有一份完整数据副本,读写请求可路由至任一 AZ,以提升性能和可用性。
在同一区域内部署的分布式存储通常通过同步复制协议(如 Paxos、Raft)保证写操作在所有 AZ 同步完成后再返回成功,从而确保读写顺序严格一致。
defTransactWriteItem(transact_write_items): # Prepare all items TransactionState = "PREPARING" for operation in transact_write_items: sendPrepareAsyncToSN(operation) waitForAllPreparesToComplete()
# Evaluate whether to commit or cancel the transaction if all_prepares_succeeded(): TransactionState = "COMMITTING" for operation in transact_write_items: sendCommitAsyncToSN(operation) waitForAllCommitsToComplete() TransactionState = "COMPLETED" return"SUCCESS" else: TransactionState = "CANCELLING" for operation in transact_write_items: sendCancellationAsyncToSN(operation) waitForAllCancellationsToComplete() TransactionState = "COMPLETED" return getReasonForCancellation()
为了实现写事务的时间戳排序机制,DynamoDB 在每次写操作(无论是单项写入还是事务写入)后都会将该事务的时间戳记录在对应项上。此外,存储节点还会为每个正在进行的事务持久化事务元数据,包括事务 ID 和时间戳。这些元数据附带在事务涉及的项上,并在分区重分裂等事件中随项迁移,从而确保事务执行不被结构变更干扰,可并行进行。一旦事务结束,这些元数据即被清除。
在协议的准备阶段,事务协调器向每个主存储节点发送一条 prepare 消息,其中包含时间戳、事务 ID 和针对该项的拟执行操作。存储节点仅当以下所有条件都满足时,才接受该事务中的该项写入请求:
if item isnotNone: if ( evaluateConditionsOnItem(item, input.conditions) and evaluateSystemRestrictions(item, input) and item.timestamp < input.timestamp and item.ongoingTransactions isNone ): item.ongoingTransaction = input.transactionId return"SUCCESS" else: return"FAILED" else: # item does not exist item = Item(input.item) if ( evaluateConditionsOnItem(input.item, input.conditions) and evaluateSystemRestrictions(input) and partition.maxDeleteTimestamp < input.timestamp ): item.ongoingTransaction = input.transactionId return"SUCCESS"
Why does DynmoDB not use the two-phase locking protocol?
While two-phase locking is used traditionally to prevent concurrent transactions from reading and writing the same data items, it has drawbacks. Locking restricts concurrency and can lead to deadlocks. Moreover, it requires a recovery mechanism to release locks when an application fails after acquiring locks as part of a transaction but before that transaction commits. To simplify the design and take advantage of low-contention workloads, DynamoDB uses an optimistic concurrency control scheme that avoids locking altogether.
With DynamoDB, what is the role of a transaction coordinator?
The Transaction Coordinator plays a central role in handling transactions that span multiple items or storage nodes. The TC is responsible for:
breaking down the transaction into individual operations and coordinating these operations across the necessary storage nodes.
ensuring that the operations follow two-phase commit and all parts of the transaction are either completed successfully or rolled back.
assigning timestamps to ensure the correct ordering of operations and managing any potential conflicts between concurrent transactions.
Is DynamoDB a relational database management system?
No, DynamoDB is not a relational database management system. It is a NoSQL database, specifically a key-value and document store. Here’s how it differs from an RDBMS:
Data Model: DynamoDB does not use tables with fixed schemas like relational databases. Instead, it stores data as key-value pairs or documents (JSON-like structure). Each item can have different attributes, and there’s no need for predefined schemas.
Relationships: Relational databases focus on managing relationships between data (using joins, foreign keys, etc.), while DynamoDB is optimized for storing large amounts of data without complex relationships between the data items.
Querying: RDBMSs typically use SQL for querying data, which allows for complex joins and aggregations. DynamoDB uses its own API for querying and does not support SQL natively. While it allows querying by primary key and secondary indexes, it doesn’t support joins.
Consistency and Transactions: DynamoDB supports eventual consistency or strong consistency for reads, while traditional relational databases typically ensure strong consistency through ACID transactions. DynamoDB has introduced transactions, but they work differently compared to those in relational databases.
Scalability: DynamoDB is designed for horizontal scalability across distributed systems, allowing it to handle very large amounts of traffic and data by automatically partitioning data. In contrast, RDBMSs are typically vertically scaled and are not as naturally distributed.
How is DynamoDB’s transaction coordinator different than Gamma’s scheduler?
DynamoDB’s transaction coordinator uses Optimistic Concurrency Control (OCC) to manage distributed transactions, ensuring atomicity without 2PC, focusing on scalability and performance in a globally distributed system.
Gamma’s scheduler, on the other hand, uses the traditional Two-Phase Locking (2PL) protocol to guarantee strong consistency in a distributed environment, prioritizing strict coordination across nodes.
Name one difference between FoundationDB and DynamoDB?
FoundationDB: FoundationDB is a multi-model database that offers a core key-value store as its foundation, but it allows you to build other data models (such as documents, graphs, or relational) on top of this key-value layer. It’s highly flexible and provides transactional support for different types of data models via layers.
DynamoDB: DynamoDB is a NoSQL key-value and document store with a fixed data model designed specifically for highly scalable, distributed environments. It does not offer the flexibility of building different models on top of its architecture and is focused on high-performance operations with automatic scaling.
What partitioning strategy does FoundationDB use to distribute key-value pairs across its StorageServers?
FoundationDB uses a range-based partitioning strategy to distribute key-value pairs across its StorageServers.
Here’s how it works:
Key Ranges: FoundationDB partitions the key-value pairs by dividing the key space into contiguous ranges. Each range of keys is assigned to a specific StorageServer.
Dynamic Splitting: The key ranges are dynamically split and adjusted based on data distribution and load. If a particular range grows too large or becomes a hotspot due to frequent access, FoundationDB will automatically split that range into smaller sub-ranges and distribute them across multiple StorageServers to balance the load.
Data Movement: When a key range is split or needs to be rebalanced, the corresponding data is migrated from one StorageServer to another without manual intervention, ensuring even distribution of data and load across the system.
Why do systems such as Nova-LSM separate storage of data from its processing?
Independent Scaling: Storage and processing resources can scale independently to meet varying load demands.
Resource Optimization: Storage nodes focus on data persistence and I/O performance, while processing nodes handle computation, improving overall resource efficiency.
Fault Tolerance: Data remains safe in storage even if processing nodes fail, ensuring high availability.
对于扁平的事务来说,其隐式地设置了一个保存点。然而在整个事务中,只有这一个保存点,因此,回滚只能回滚到事务开始时的状态。保存点用 SAVE WORK 函数来建立,通知系统记录当前的处理状态。当出现问题时,保存点能用作内部的重启动点,根据应用逻辑,决定是回到最近一个保存点还是其他更早的保存点。下图显示了在事务中使用保存点。
上图中,灰色背景部分的操作表示由 ROLLBACK WORK 而导致部分回滚,实际上并没有执行的操作。当用 BEGIN WORK 开启一个事务时,隐式地包含了一个保存点;当事务通过 ROLLBACK WORK : 2 发出部分回滚命令时,事务回滚到保存点 2,接着依次执行,并再次执行到 ROLLBACK WORK : 7,直到最后的 COMMIT WORK 操作,这时表示事务结束,除灰色阴影部分的操作外,其余操作都已经执行,并且提交。
mysql>SELECT @@version\G; ERROR 2006 (HY000): MySQL server has gone away No connection. Trying to reconnect... Connection id: 54 Current database: test ***************************1.row*************************** @@version: 5.1.45-log 1rowinset (0.00 sec)
在这个例子中,设置了 completion_type=2 后,执行 COMMIT WORK 不仅提交了事务,而且释放(关闭)了当前连接。重新执行任何查询时,客户端都会发现与服务器的连接已断开,并尝试重新连接。
SAVEPOINT 记录了一个保存点,可以通过 ROLLBACK TO SAVEPOINT 来回滚到某个保存点,但是如果回滚到一个不存在的保存点,会抛出异常:
1 2 3 4 5
mysql>BEGIN; Query OK, 0rows affected (0.00 sec)
mysql>ROLLBACKTOSAVEPOINT t1; ERROR 1305 (42000): SAVEPOINT t1 does not exist
ALTER DATABASE … UPGRADE DATA DIRECTORY NAME ALTER EVENT ALTERPROCEDURE ALTER TABLE ALTERVIEW CREATE DATABASE CREATE EVENT CREATE INDEX CREATEPROCEDURE CREATE TABLE CREATETRIGGER CREATEVIEW DROP DATABASE DROP EVENT DROP INDEX DROPPROCEDURE DROPTABLE DROPTRIGGER DROPVIEW RENAME TABLE TRUNCATETABLE
用来隐式地修改 MySQL 架构的操作:
1 2 3 4 5 6
CREATEUSER DROPUSER GRANT RENAME USER REVOKE SET PASSWORD
管理语句:
1 2 3 4 5 6
ANALYZE TABLE CACHE INDEX CHECKTABLE LOAD INDEX INTO CACHE OPTIMIZE TABLE REPAIR TABLE
虽然在上面的例子中,Log sequence number 和 Log flushed up to 的值是相同的,但是在实际生产环境中,该值有可能是不同的。因为在一个事务中从日志缓冲刷新到重做日志文件并不只是在事务提交时发生,每秒都会有从日志缓冲刷新到重做日志文件的动作。下面是在生产环境下重做日志的信息的示例。
当 InnoDB 存储引擎的压力非常大时,并不能高效地进行 purge 操作。那么 history list 的长度会变得越来越长。全局动态参数 innodb_max_purge_lag 用来控制 history list 的长度,若长度大于该参数时,其会延缓 DML 的操作。该参数默认值为 0,表示不对 history list 做任何限制。当大于 0 时,就会延缓 DML 的操作,其延缓的算法为:
这个问题最早在 2010 年的 MySQL 数据库大会中提出,Facebook MySQL 技术组、Percona 公司都提出过解决方案。最后由 MariaDB 数据库的开发人员 Kristian Nielsen 完成了最终的“完美”解决方案。在这种情况下,不但 MySQL 数据库上层的二进制日志写入是 group commit 的,InnoDB 存储引擎层也是 group commit 的。此外还移除了原先的锁 prepare_commit_mutex,从而大大提高了数据库的整体性。MySQL 5.6 采用了类似的实现方式,并将其称为 Binary Log Group Commit(BLGC)。
假设读事务开启了一个 ReadView,这个 ReadView 里面记录了当前活跃事务的 ID 列表(444、555、665),以及最小事务 ID(444)和最大事务 ID(666)。当然还有自己的事务 ID 520,也就是 creator_trx_id。它要读的这行数据的写事务 ID 是 x,也就是 DB_TRX_ID。
事务冲突与回滚:如果多个事务在同一行上发生冲突(例如,事务 A 在修改一行数据时,事务 B 也试图修改同一行数据),事务 B 会等待事务 A 完成。当事务 A 提交后,事务 B 才能继续进行。如果事务 A 回滚,那么事务 B 仍然可以继续修改该行,因为回滚后数据恢复到了事务 A 之前的状态。
如果其他三个特性都能够得到保证,那一致性也就能得到保证了。例如:
如果一个事务回滚,原子性确保数据库回到之前的状态;
隔离性确保事务之间的干扰最小化,避免不一致;
持久性确保事务提交后修改不会丢失。
分布式事务
在 MySQL 数据库中,InnoDB 存储引擎提供了对 XA 事务的支持,并通过 XA 事务来实现分布式事务。分布式事务指的是允许多个独立的事务资源(transactional resources)参与到一个全局的事务中。事务资源通常是关系型数据库系统,但也可以是其他类型的资源。全局事务要求其中的所有参与事务要么都提交,要么都回滚,这对事务原有的 ACID 要求提出了更高的要求。此外,在使用分布式事务时,InnoDB 存储引擎的事务隔离级别必须设置为 SERIALIZABLE。
XA 事务允许在不同数据库之间进行分布式事务。比如,一台服务器上运行 MySQL 数据库,另一台服务器上运行 Oracle 数据库,甚至还可能有一台运行 SQL Server 数据库,只要所有参与全局事务的节点都支持 XA 事务即可。分布式事务在银行系统的转账场景中比较常见,例如用户 David 需要从上海的账户转账 10 000 元到北京用户 Mariah 的银行卡中:
1 2 3 4 5
# Bank@Shanghai: UPDATE account SET money = money -10000WHEREuser='David';
# Bank@Beijing: UPDATE account SET money = money +10000WHEREuser='Mariah';
在这种情况下,一定需要使用分布式事务来保证数据的安全性。如果操作不能全部提交或全部回滚,那么任何一个节点出现问题都会导致严重后果:要么 David 的账户被扣款但 Mariah 没收到钱,要么 David 的账户没有扣款但 Mariah 收到钱。
在上图中,如果执行完 ①、② 后在步骤 ③ 之前 MySQL 数据库发生了宕机,则会发生主从不一致的情况。为了解决这个问题,MySQL 数据库在 binlog 与 InnoDB 存储引擎之间采用 XA 事务。当事务提交时,InnoDB 存储引擎会先做一个 PREPARE 操作,将事务的 xid 写入,接着进行二进制日志的写入,如下图所示。如果在 InnoDB 存储引擎提交前,MySQL 数据库宕机了,那么 MySQL 数据库在重启后会先检查准备的 UXID 事务是否已经提交,若没有,则在存储引擎层再进行一次提交操作。
不好的事务习惯
在循环中提交
开发人员可能会在循环中进行事务的提交,如下(可想象成 Java 中的某个方法):
1 2 3 4 5 6 7 8 9 10
CREATEPROCEDURE load1(count INT UNSIGNED) BEGIN DECLARE s INT UNSIGNED DEFAULT1; DECLARE c CHAR(80) DEFAULT REPEAT('a',80); WHILE s <= count DO INSERT INTO t1 SELECTNULL, c; COMMIT; SET s = s +1; END WHILE; END;
CREATEPROCEDURE load3(count INT UNSIGNED) BEGIN DECLARE s INT UNSIGNED DEFAULT1; DECLARE c CHAR(80) DEFAULT REPEAT('a',80); START TRANSACTION; WHILE s <= count DO INSERT INTO t1 SELECTNULL, c; SET s = s +1; END WHILE; COMMIT; END;
Divide-and-Conquer (or separation of concerns). FDB decouples the transaction management system (write path) from the distributed storage (read path) and scales them independently. Within the transaction management system, processes are assigned various roles representing different aspects of transaction management. Furthermore, cluster-wide orchestrating tasks, such as overload control and load balancing are also divided and serviced by additional heterogeneous roles.
Make failure a common case. For distributed systems, failure is a norm rather than an exception. To cope with failures in the transaction management system of FDB, we handle all failures through the recovery path: the transaction system proactively shuts down when it detects a failure. Thus, all failure handling is reduced to a single recovery operation, which becomes a common and well-tested code path. To improve availability, FDB strives to minimize Mean-Time-To-Recovery (MTTR). In our production clusters, the total time is usually less than five seconds.
Simulation testing. FDB relies on a randomized, deterministic simulation framework for testing the correctness of its distributed database. Simulation tests not only expose deep bugs, but also boost developer productivity and the code quality of FDB.
Architecture
The control plane is responsible for persisting critical system metadata, that is, the configuration of transaction systems, on Coordinators.
These Coordinators form a Paxos group and elect a ClusterController.
The ClusterController monitors all servers in the cluster and recruits three processes, Sequencer, DataDistributor, and Ratekeeper, which are re-recruited if they fail or crash.
The DataDistributor is responsible for monitoring failures and balancing data among StorageServers.
Ratekeeper provides overload protection for the cluster.
The data plane is responsible for transaction processing and data storage. FDB chooses an unbundled architecture:
A distributed transaction management system (TS) consists of a Sequencer, Proxies, and Resolvers, all of which are stateless processes.
The Sequencer assigns a read and a commit version to each transaction.
Proxies offer MVCC read versions to clients and orchestrate transaction commits.
Resolvers check for conflicts among transactions.
A log system (LS) stores Write-Ahead-Log (WAL) for TS, and a separate distributed storage system (SS) is used for storing data and servicing reads. The LS contains a set of LogServers and the SS has a number of StorageServers. LogServers act as replicated, sharded, distributed persistent queues, each queue storing WAL data for a StorageServer.
Clients read from sharded StorageServers, so reads scale linearly with the number of StorageServers.
Writes are scaled by adding more Proxies, Resolvers, and LogServers.
The control plane’s singleton processes (e.g., ClusterController and Sequencer) and Coordinators are not performance bottlenecks; they only perform limited metadata operations. 因为元数据操作少且简单,且与两者无关的数据读写是并行扩展的(如上面两行加粗字体所述)。
Bootstrapping
FDB has no dependency on external coordination services. All user data and most system metadata (keys that start with 0xFF prefix) are stored in StorageServers. The metadata about StorageServers is persisted in LogServers, and the LogServers configuration data is stored in all Coordinators.
The Coordinators are a disk Paxos group; servers attempt to become the ClusterController if one does not exist.
A newly elected ClusterController reads the old LS configuration from the Coordinators and spawns a new TS and LS.
Proxies recover system metadata from the old LS, including information about all StorageServers.
The Sequencer waits until the new TS finishes recovery, then writes the new LS configuration to all Coordinators. The new transaction system is then ready to accept client transactions.
Reconfiguration
The Sequencer process monitors the health of Proxies, Resolvers, and LogServers. Whenever there is a failure in the TS or LS, or the database configuration changes, the Sequencer terminates. The ClusterController detects the Sequencer failure, then recruits and bootstraps a new TS and LS. In this way, transaction processing is divided into epochs, where each epoch represents a generation of the transaction management system with its own Sequencer.
End-to-end transaction processing
Transaction Start and Read Operations:
A client starts a transaction by contacting a Proxy to obtain a read version (timestamp).
The Proxy requests a read version from the Sequencer that is greater than all previously issued commit versions and sends it to the client.
The client then reads from StorageServers at this specific read version.
Buffered Write Operations:
Client writes are buffered locally and not sent to the cluster immediately.
Read-your-write semantics are preserved by combining the database lookups with the client’s uncommitted writes.
Transaction Commit:
When the client commits, it sends the transaction data (read and write sets) to a Proxy, waiting for either a commit or abort response.
The Proxy commits a transaction in three steps:
Obtain Commit Version: The Proxy requests a commit version from the Sequencer that is larger than all current read or commit versions.
Conflict Check: The Proxy sends transaction data to the partitioned Resolvers, which check for read-write conflicts. If no conflicts are found, the transaction proceeds; otherwise, it is aborted.
Persist to Log Servers: The transaction is sent to LogServers for persistence, and after all LogServers acknowledge, the transaction is considered committed. The Proxy then reports the committed version to the Sequencer and sends the response back to the client.
Applying Writes:
StorageServers continuously pull mutation logs from LogServers and apply the committed changes to disk.
Read-Only Transactions and Snapshot Reads:
Read-only transactions are serializable (at the read version) and high-performance (thanks to MVCC), allowing the client to commit locally without contacting the database, which is particularly important since most transactions are read-only.
Snapshot reads relax the isolation property of a transaction, reducing conflicts by allowing concurrent writes without conflicting with snapshot reads.
FoundationDB (FDB) using Serializable Snapshot Isolation (SSI) by combining Optimistic Concurrency Control (OCC) with Multi-Version Concurrency Control (MVCC).
Transaction Versions
Each transaction receives a read version and a commit version from the Sequencer.
The read version ensures that the transaction observes the results of all previously committed transactions, and the commit version is greater than all current read or commit versions, establishing a serial order for transactions.
Log Sequence Number (LSN)
The commit version serves as the LSN, defining a serial history of transactions.
To ensure no gaps between LSNs, the Sequencer also returns the previous LSN with each commit. Both the LSN and previous LSN are sent to Resolvers and LogServers to enforce serial processing of transactions.
Conflict Detection
FDB uses a lock-free conflict detection algorithm similar to write-snapshot isolation, but the commit version is chosen before conflict detection, enabling efficient batch processing of version assignments and conflict detection.
The key space is divided among multiple Resolvers, allowing conflict detection to be parallelized. A transaction can commit only if all Resolvers confirm no conflicts.
Handling Aborted Transactions
If a transaction is aborted, some Resolvers may have already updated their history, leading to possible “false positive” conflicts for other transactions. However, this is rare because most transactions’ key ranges fall within one Resolver, and the effects of false positives are limited to a short MVCC window (5 seconds).
Efficiency of OCC
The OCC design avoids the complexity of acquiring and releasing locks, simplifying interactions between the Transaction System (TS) and Storage Servers (SS).
While OCC may result in some wasted work due to aborted transactions, FDB’s conflict rate in production is low (less than 1%), and clients can simply restart aborted transactions.
Logging protocol
Commit Logging:
Once a Proxy decides to commit a transaction, it sends the transaction’s changes (mutations) to the LogServers responsible for the modified key ranges. Other LogServers receive an empty message.
The log message includes the current and previous Log Sequence Number (LSN) from the Sequencer and the largest known committed version (KCV) of the Proxy.
The LogServers reply to the Proxy once the log data is durably stored. The Proxy updates its KCV if all replica LogServers acknowledge and the LSN is larger than the current KCV.
Shipping Redo Logs:
Shipping the redo log from LogServers to StorageServers happens in the background and is not part of the commit path, improving performance.
Applying Redo Logs:
StorageServers apply non-durable redo logs from LogServers to an in-memory index. In most cases, this happens before any client reads are processed, ensuring low-latency multi-version reads.
If the requested data is not yet available on a StorageServer, the client either waits or retries at another replica. If both reads time out, the client can restart the transaction.
I/O Efficiency:
Since log data is already durable on LogServers, StorageServers can buffer updates in memory and write batches to disk periodically, improving input/output (I/O) efficiency.
What if a StorageServer is lagging behind on applying the redo logs and a client requests a version of a key pair it does not have?
Wait for a threshold for when known-committed-version is greater than or equal to the read version
If timeout, the client asks another StorageServer that stores the key
Return error “request for a future version” (FDB error code 1009)
What if there is no further transaction logs to redo?
Without new transactions issued from the client, proxies still generate empty transactions to advance the known-committed-version
Known-committed-version and LSN of each transaction are sent to all LogServers (limit scalability on writes)
Transaction system recovery
Simplified Recovery
Unlike traditional databases that require undo log processing, FoundationDB avoids this step by making the redo log processing the same as the normal log forward path. StorageServers pull logs from LogServers and apply them in the background.
Failure Detection and New Transaction System (TS)
Upon detecting a failure, a new TS is recruited. The new TS can start accepting transactions even before all old logs are fully processed. Recovery focuses on finding the end of the redo log, allowing StorageServers to asynchronously replay the logs from that point.
Epoch-based Recovery
The recovery process is handled per epoch. The ClusterController locks the old TS configuration, stops old LogServers from accepting new transactions, recruits a new set of transaction components (Sequencer, Proxies, Resolvers, and LogServers), and writes the new TS configuration to the Coordinators.
Stateless components like Proxies and Resolvers don’t require special recovery, but LogServers, which store committed transaction logs, must ensure all data is durable and retrievable by StorageServers.
Recovery Version (RV)
The recovery focuses on determining the Recovery Version (RV), which is essentially the end of the redo log. The Sequencer collects data from the old LogServers, specifically the Durable Version (DV) (maximum LSN persisted) and KCV (maximum committed version) from each.
Once enough LogServers have responded, the Previous Epoch Version (PEV) is established (the maximum of all KCVs). The start version of the new epoch is PEV + 1, and the minimum DV becomes the RV.
Log Copying and Healing
Logs between PEV + 1 and RV are copied from old LogServers to the new ones to restore replication in case of LogServer failures. This copying process is lightweight since it only covers a few seconds of logs.
Rollback and Transaction Processing
The first transaction after recovery is a special recovery transaction that informs StorageServers of the RV, so they can discard in-memory multi-versioned data beyond the RV. StorageServers then pull data larger than the PEV from the new LogServers.
The rollback process simply discards in-memory multi-versioned data, as persistent data is only written to disk once it leaves the MVCC window.
Replication
Metadata Replication:
System metadata related to the control plane is stored on Coordinators using the Active Disk Paxos protocol. As long as a majority (quorum) of Coordinators are operational, the metadata can be recovered in case of failure.
Log Replication:
When a Proxy writes logs to LogServers, each log record is replicated synchronously across k = f + 1 LogServers (where f is the number of allowed failures). The Proxy only sends a commit response to the client after all k LogServers have successfully persisted the log. If a LogServer fails, a transaction system recovery is triggered.
Storage Replication:
Each key range (shard) is asynchronously replicated across k = f + 1 StorageServers. These StorageServers form a team. A StorageServer typically hosts multiple shards, distributing its data across several teams. If a StorageServer fails, the DataDistributor moves the data from teams with the failed server to other healthy teams.
To prevent data loss in case of simultaneous failures, FoundationDB ensures that no more than one process in a replica group is placed within the same fault domain (e.g., a host, rack, or availability zone). As long as one process in each team is operational, no data is lost, provided at least one fault domain remains available.
Simulation testing
Deterministic Simulation:
FoundationDB uses deterministic discrete-event simulation to test its distributed system. This simulation runs real database code along with randomized synthetic workloads and fault injection to uncover bugs.
Determinism ensures that bugs are reproducible and can be investigated thoroughly.
Fault Injection:
The simulation tests system resilience by injecting various faults, such as machine, rack, or data center failures, network issues, disk corruption, and delays.
Randomization of these faults increases the diversity of tested states, allowing for a wide range of potential issues to be examined.
“Buggification” is a technique used to deliberately introduce rare or unusual behaviors (e.g., unnecessary delays, errors) in the system to stress-test its handling of non-standard conditions.
Swarm Testing:
Swarm testing increases simulation diversity by using random cluster sizes, configurations, workloads, and fault injection parameters.
This ensures that a broad range of scenarios is covered in testing, allowing for the discovery of rare bugs.
Test Oracles:
Test oracles are built into the system to verify key properties like transaction atomicity, isolation, and recoverability. Assertions check these properties to detect failures during simulation.
They help confirm that the system’s expected behaviors are maintained, even under stressful conditions.
Bug Detection Efficiency:
The simulation runs faster than real-time, allowing FoundationDB to quickly discover and trace bugs. The parallel nature of testing accelerates the process of finding bugs, particularly before major releases.
This approach uncovers bugs that may not appear during real-time testing, especially for issues that require long-running operations.
It cannot test third-party libraries or external dependencies, focusing mainly on FoundationDB’s internal code and behaviors.
Lessons learned
Architecture Design
Divide-and-Conquer Principle: Separating the transaction system from the storage layer allows for independent scaling and deployment of resources, enhancing both flexibility and performance.
LogServers as Witness Replicas: In multi-region deployments, LogServers reduce the need for full StorageServer replicas while maintaining high availability.
Role Specialization: The design enables the creation of specialized roles, like separating DataDistributor and Ratekeeper from the Sequencer, and separating Proxies into Get-Read-Version and Commit Proxies, which improves performance and makes the system extensible.
Decoupling Enhances Extensibility: This design pattern allows features like replacing SQLite with RocksDB and adding new roles or functions without overhauling the entire system.
Simulation Testing
High Productivity: FDB’s deterministic simulation testing enables bugs to be found and reproduced quickly. This approach has improved developer productivity and system reliability by reducing debugging time and improving test coverage.
Reliability: FDB has operated without any data corruption over several years of deployment (e.g., CloudKit), thanks to rigorous simulation testing. Simulation has allowed ambitious rewrites and improvements to be made safely.
Eliminating Dependencies: Simulation testing helped find bugs in external dependencies, leading to FDB replacing Apache Zookeeper with its own Paxos implementation. This change resulted in no further production bugs.
Fast Recovery
Simplifies Upgrades: FDB allows fast recovery by restarting all processes simultaneously, typically within seconds, simplifying software upgrades and configuration changes. This method has been extensively tested and used in Apple’s production clusters.
Bug Healing: Fast recovery can automatically resolve certain latent bugs, similar to software rejuvenation, by resetting system states.
5-Second MVCC Window
Memory Efficiency: FDB uses a 5-second MVCC (Multi-Version Concurrency Control) window to limit memory usage in transaction systems and storage servers. This time window is long enough for most OLTP workloads, exposing inefficiencies if the transaction exceeds 5 seconds.
TaskBucket Abstraction: Long-running processes, like backups, are broken into smaller transactions that fit within the 5-second window. FDB implements this through an abstraction called TaskBucket, which simplifies splitting large transactions into manageable jobs.
Questions
With FDB, what operations does a transaction commit perform when the transaction only reads the value of data items?
Read Version Retrieval: The client requests a read version from a Proxy via the Sequencer, which guarantees the read version is greater than or equal to any committed version.
Read Operation: The client reads the requested data at this specific read version from the StorageServers. The reads are served by the StorageServers, which are guaranteed to provide data consistent with the requested version.
No Writes or Conflicts: Since the transaction is read-only, there is no write set or conflicts to check. The transaction simply ends, and no data is written or modified, meaning it does not interact with LogServers or commit any changes.
Commit: Even though no actual commit occurs (because there’s no data change), the transaction is marked as successfully completed after the reads are done.
With FDB, is it possible for multiple resolvers to participate in the decision whether to commit or abort a write transaction?
Yes, multiple Resolvers can participate in the decision to commit or abort a write transaction in FDB. Here’s how it works:
Conflict Detection: When a transaction writes data, the write set (the keys it wants to write) is sent to a set of Resolvers. Each Resolver is responsible for a specific portion of the key space. Multiple Resolvers can be involved in checking the transaction’s read and write sets to detect conflicts (read-write conflicts or write-write conflicts).
Parallel Conflict Checking: Since the key space is partitioned, different Resolvers check different key ranges in parallel. A transaction can only commit if all Resolvers agree that there are no conflicts.
With FDB, what if a StorageServer is lagging behind on applying the redo logs and a client requests a version of a key pair it does not have?
Client Waits: The client can choose to wait for the StorageServer to catch up by applying the redo logs. Once the StorageServer finishes replaying the logs and reaches the required version, it can serve the requested data.
Retry at Another Replica: If the StorageServer does not have the requested version yet, the client can try to read from another replica of the key. FDB typically stores multiple replicas of data across different StorageServers, so the client can retry the request from a replica that is up to date.
Transaction Restart: If neither replica has the requested version or the delay is too long, the client may restart the transaction. Since FoundationDB uses MVCC (Multi-Version Concurrency Control), restarting the transaction allows it to obtain a fresh version of the key from an up-to-date StorageServer.
Consider a database for students enrolling in courses and professors teaching those courses. Provide a SDM model of this database?
Students: base concrete object class.
member property: student_id, name, age, email, department_id.
identifier: student_id.
Professors: base concrete object class.
member property: professor_id, name, age, email, department_id.
identifier: professor_id.
Courses: base concrete object class
member property: course_id, name, location, start_time, end_time, department_id.
derived member property: professor as Professors.professor_id.
identifier: course_id.
Enrollment: base duration event class.
member property: enrollment_id, date_of_enrollment.
member participant: student in Students, course in Courses.
identifier: enrollment_id.
Departments: abstract Students and Professors on common value of department_id.
derived member property: department_id as distinct value of (Students.department_id union Professors.department_id).
What is the difference between a monolithic database management system and a disaggregated database management system?
Feature
Monolithic DBMS
Disaggregated DBMS
Architecture
All components tightly integrated into a single system
Components like storage, computation, and query processing are separated
Scalability
Scales through vertical scaling (adding resources to the single server)
Scales through horizontal scaling (independent scaling of storage and compute)
Performance Bottlenecks
May face bottlenecks as the system grows
Components are independently optimized, reducing bottlenecks
Resource Management
Storage and compute resources are tightly coupled, hard to manage separately
Storage and compute resources can be managed independently, offering flexibility
Complexity
Easier to deploy and manage initially, but complexity increases with scale
More complex to manage and coordinate different components
Cost
Pay for all resources, even if they are not fully utilized
Can optimize resource usage and costs by scaling components independently
Consistency
Strong data consistency due to tight integration
Requires additional mechanisms to ensure consistency across components
With Gamma and its data flow execution paradigm, how does the system know when the execution of a parallel query involving multiple operators is complete?
Data Dependency Graph: The query execution is modeled as a directed acyclic graph (DAG), where each node represents an operator (e.g., selection, join). Data flows between operators, and the system tracks the completion of each operator based on this graph.
Completion Signals: Each parallel operator sends a “done” signal once it finishes processing its data partition. The system monitors these signals to determine when all operators have finished.
Coordinator: A central coordinator tracks the progress of parallel tasks. When all tasks report completion, the system declares the query execution as complete.