Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: persist commit index in LogStore to accelerate recovery #613

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
2e5a8a0
feat: add CommitTrackingLogStore interface for commit index management
peterxcli Sep 1, 2024
ffc6b3b
chore: remove non-idiomatic type assert func
peterxcli Sep 3, 2024
7383d96
feat(raft): add fast recovery mode for quicker log application
peterxcli Sep 4, 2024
f6295e0
feat(raft): add recovery from committed logs during startup
peterxcli Sep 4, 2024
f2ae7a9
refactor(store): rename ReadCommitIndex to GetCommitIndex for consist…
peterxcli Sep 6, 2024
ce1895c
fix: also set inmem commit index when revocer log commit progress fro…
peterxcli Sep 10, 2024
ab50a58
perf: optimize startup recovery by skipping duplicated log replay
peterxcli Sep 10, 2024
4e7e04b
refactor(inmem-commit-tracking-store): store commit index in memory u…
peterxcli Sep 13, 2024
41df55e
chore: fix typo in recoverFromCommittedLogs function name
peterxcli Sep 13, 2024
400a27d
refactor(raft): update parameter name in persistCommitIndex function
peterxcli Sep 13, 2024
e2617e8
refactor(raft): set commit index in memory before `StoreLogs`
peterxcli Sep 13, 2024
6daca47
refactor(raft): fix condition for skipping recovery in `recoverFromCo…
peterxcli Sep 18, 2024
cc09317
feat(raft): add commit tracking logs and fast recovery tests
peterxcli Sep 18, 2024
fe57b32
docs(config): update comments for FastRecovery mechanism
peterxcli Sep 19, 2024
20e8701
refactor(inmem-commit-tracking-store): simplify in-mem log tracking s…
peterxcli Sep 19, 2024
6f146e1
fix: rename persistCommitIndex to tryPersistCommitIndex
peterxcli Sep 19, 2024
a8438b0
chore(raft): rename tryPersistCommitIndex to tryStageCommitIndex for …
peterxcli Sep 20, 2024
5e6d8a4
refactor(log): introduce StagCommitIndex for optimized atomic persist…
peterxcli Sep 20, 2024
e248f00
fix(raft): correct CommitTrackingLogStore implementation
peterxcli Sep 24, 2024
2a913ab
feat(raft): improve fast recovery error handling and commit index val…
peterxcli Sep 24, 2024
7cd6732
feat: add `CommitTrackingLogStore` interface check and adjust return …
peterxcli Oct 9, 2024
92c04a0
refactor: improve type assertion for log store in TestRaft_FastRecovery
peterxcli Oct 9, 2024
8e8ba07
feat: add warning log for unsupported fast recovery
peterxcli Oct 10, 2024
2020cab
refactor: move commitIndex retrieve into `tryStageCommitIndex`
peterxcli Oct 10, 2024
2a7d584
refactor: remove error from return field of recoverFromCommittedLogs
peterxcli Oct 10, 2024
bdac45b
refactor: rename FastRecovery and revert the stageCommittedIdx change
peterxcli Oct 11, 2024
ed47a25
docs: documented GetCommitIndex in CommitTrackingLogStore interface
peterxcli Oct 11, 2024
ad87d86
docs: change fastRecovery flag to recoverCommittedLog in all document…
peterxcli Oct 11, 2024
30fc43e
refactor: add a new ErrIncompatibleLogStore for recoverFromCommittedLogs
peterxcli Oct 11, 2024
e797962
docs: clarify RestoreCommittedLogs configuration requirement
peterxcli Oct 11, 2024
500567f
refactor: rename recoverFromCommittedLogs to restoreFromCommittedLogs
peterxcli Oct 11, 2024
cfffcb5
refactor!: update MakeCluster functions to return error
peterxcli Oct 11, 2024
560c0b9
test: add test for RestoreCommittedLogs with incompatible log store
peterxcli Oct 11, 2024
8c722fa
Revert "refactor!: update MakeCluster functions to return error"
peterxcli Oct 12, 2024
300a6e7
refactor: update makeCluster to return errors
peterxcli Oct 12, 2024
8d11a28
Use wrapped err
peterxcli Oct 12, 2024
1bdf161
docs: clarify GetCommitIndex behavior in CommitTrackingLogStore inter…
peterxcli Oct 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ var (
// ErrLeadershipTransferInProgress is returned when the leader is rejecting
// client requests because it is attempting to transfer leadership.
ErrLeadershipTransferInProgress = errors.New("leadership transfer in progress")

// ErrIncompatibleLogStore is returned when the log store does not support
// or implement some required methods.
ErrIncompatibleLogStore = errors.New("log store does not implement some required methods or malformed")
)

// Raft implements a Raft node.
Expand Down Expand Up @@ -217,6 +221,10 @@ type Raft struct {
// preVoteDisabled control if the pre-vote feature is activated,
// prevote feature is disabled if set to true.
preVoteDisabled bool

// RestoreCommittedLogs is used to enable restore committed logs mode
// restore committed logs mode is disabled if set to false.
RestoreCommittedLogs bool
}

// BootstrapCluster initializes a server's storage with the given cluster
Expand Down Expand Up @@ -566,6 +574,7 @@ func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps Sna
followerNotifyCh: make(chan struct{}, 1),
mainThreadSaturation: newSaturationMetric([]string{"raft", "thread", "main", "saturation"}, 1*time.Second),
preVoteDisabled: conf.PreVoteDisabled || !transportSupportPreVote,
RestoreCommittedLogs: conf.RestoreCommittedLogs,
}
if !transportSupportPreVote && !conf.PreVoteDisabled {
r.logger.Warn("pre-vote is disabled because it is not supported by the Transport")
Expand All @@ -585,9 +594,14 @@ func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps Sna
return nil, err
}

if err := r.restoreFromCommittedLogs(); err != nil {
return nil, err
}

// Scan through the log for any configuration change entries.
snapshotIndex, _ := r.getLastSnapshot()
for index := snapshotIndex + 1; index <= lastLog.Index; index++ {
lastappliedIndex := r.getLastApplied()
for index := max(snapshotIndex, lastappliedIndex) + 1; index <= lastLog.Index; index++ {
var entry Log
if err := r.logs.GetLog(index, &entry); err != nil {
r.logger.Error("failed to get log", "index", index, "error", err)
Expand Down Expand Up @@ -697,6 +711,40 @@ func (r *Raft) tryRestoreSingleSnapshot(snapshot *SnapshotMeta) bool {
return true
}

// restoreFromCommittedLogs recovers the Raft node from committed logs.
func (r *Raft) restoreFromCommittedLogs() error {
if !r.RestoreCommittedLogs {
return nil
}

// If the store implements CommitTrackingLogStore, we can read the commit index from the store.
// This is useful when the store is able to track the commit index and we can avoid replaying logs.
store, ok := r.logs.(CommitTrackingLogStore)
if !ok {
r.logger.Warn("restore committed logs enabled but log store does not support it", "log_store", fmt.Sprintf("%T", r.logs))
return ErrIncompatibleLogStore
}

commitIndex, err := store.GetCommitIndex()
if err != nil {
r.logger.Error("failed to get commit index from store", "error", err)
return err
}

lastIndex, err := r.logs.LastIndex()
if err != nil {
r.logger.Error("failed to get last log index from store", "error", err)
return err
}
if commitIndex > lastIndex {
commitIndex = lastIndex
}

r.setCommitIndex(commitIndex)
r.processLogs(commitIndex, nil)
return nil
}

func (r *Raft) config() Config {
return r.conf.Load().(Config)
}
Expand Down
13 changes: 13 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,19 @@ type Config struct {
// PreVoteDisabled deactivate the pre-vote feature when set to true
PreVoteDisabled bool

// RestoreCommittedLogs controls if the Raft server should use the restore committed logs
// mechanism. Restore committed logs requires a LogStore implementation that
// support commit tracking. When such a store is used and this config
// enabled, raft nodes will replay all known-committed logs on disk
// before completing `NewRaft` on startup. This is mainly useful where
// the application allows relaxed-consistency reads from followers as it
// will reduce how far behind the follower's FSM is when it starts. If all reads
// are forwarded to the leader then there won't be observable benefit from this feature.
//
// Notice: If this is enabled, the log store MUST implement the CommitTrackingLogStore
// interface. Otherwise, Raft will fail to start and return ErrIncompatibleLogStore.
RestoreCommittedLogs bool

// skipStartup allows NewRaft() to bypass all background work goroutines
skipStartup bool
}
Expand Down
30 changes: 30 additions & 0 deletions inmem_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ package raft
import (
"errors"
"sync"
"sync/atomic"
)

var _ CommitTrackingLogStore = &InmemCommitTrackingStore{}

// InmemStore implements the LogStore and StableStore interface.
// It should NOT EVER be used for production. It is used only for
// unit tests. Use the MDBStore implementation instead.
Expand Down Expand Up @@ -131,3 +134,30 @@ func (i *InmemStore) GetUint64(key []byte) (uint64, error) {
defer i.l.RUnlock()
return i.kvInt[string(key)], nil
}

type commitIndexTrackingLog struct {
log *Log
CommitIndex uint64
}
type InmemCommitTrackingStore struct {
lalalalatt marked this conversation as resolved.
Show resolved Hide resolved
InmemStore
commitIndex atomic.Uint64
}

// NewInmemCommitTrackingStore returns a new in-memory backend that tracks the commit index. Do not ever
// use for production. Only for testing.
func NewInmemCommitTrackingStore() *InmemCommitTrackingStore {
i := &InmemCommitTrackingStore{
InmemStore: *NewInmemStore(),
}
return i
}

func (i *InmemCommitTrackingStore) StageCommitIndex(index uint64) error {
i.commitIndex.Store(index)
return nil
}

func (i *InmemCommitTrackingStore) GetCommitIndex() (uint64, error) {
return i.commitIndex.Load(), nil
}
lalalalatt marked this conversation as resolved.
Show resolved Hide resolved
25 changes: 25 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,28 @@ func emitLogStoreMetrics(s LogStore, prefix []string, interval time.Duration, st
}
}
}

type CommitTrackingLogStore interface {
LogStore

// StageCommitIndex stages a new commit index to be persisted.
// The staged commit index MUST only be persisted in a manner that is atomic
// with the following StoreLogs call in the face of a crash.
// This allows the Raft implementation to optimize commit index updates
// without risking inconsistency between the commit index and the log entries.
//
// The implementation MUST NOT persist this value separately from the log entries.
// Instead, it should stage the value to be written atomically with the next
// StoreLogs call.
//
// GetCommitIndex MUST never return a value higher than the last index in the log,
// even if a higher value has been staged with this method.
//
// idx is the new commit index to stage.
StageCommitIndex(idx uint64) error
dhiaayachi marked this conversation as resolved.
Show resolved Hide resolved

// GetCommitIndex returns the latest persisted commit index from the latest log entry
// in the store at startup.
// It is ok to return a value higher than the last index in the log (But it should never happen).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// It is ok to return a value higher than the last index in the log (But it should never happen).
// GetCommitIndex should not return a value higher than the last index in the log. If that happens, the last index in the log will be used.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also document here that GetCommitIndex need to return 0,nil when no commit index is found in the log.

GetCommitIndex() (uint64, error)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would a GetCommitIndex() could be implemented in a real store? Would it read the latest stored log and return the commit index associated to it? What if it don't find any because those logs were stored using a store that don't support fast-recovery?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For BoltDB, I imagine commit index would be a single KV in a separate bucket from logs so it would just read that and return it.

For WAL I anticipated extending the format slightly so that each commit entry in the log stores the most recently staged commit index and then re-populated that into memory when we open the log an scan it like we do with indexes.

If there is no commit index stored, we should just return 0, nil which is always safe and has the same behavior as current code I think right?

Copy link
Contributor

@dhiaayachi dhiaayachi Oct 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is no commit index stored, we should just return 0, nil which is always safe and has the same behaviour as current code I think right?

I agree! I think that should be documented though. Because the API allow erroring on GetCommitIndex() it could easily be mistaken as a possible error case.

}
22 changes: 22 additions & 0 deletions raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,9 @@ func (r *Raft) dispatchLogs(applyLogs []*logFuture) {
r.leaderState.inflight.PushBack(applyLog)
}

commitIndex := r.getCommitIndex()
schmichael marked this conversation as resolved.
Show resolved Hide resolved
r.tryStageCommitIndex(commitIndex)

// Write the log entry locally
if err := r.logs.StoreLogs(logs); err != nil {
r.logger.Error("failed to commit logs", "error", err)
Expand Down Expand Up @@ -1385,6 +1388,20 @@ func (r *Raft) prepareLog(l *Log, future *logFuture) *commitTuple {
return nil
}

// tryStageCommitIndex updates the commit index in persist store if restore committed logs is enabled and log store implements CommitTrackingLogStore.
func (r *Raft) tryStageCommitIndex(commitIndex uint64) {
if !r.RestoreCommittedLogs {
return
}
store, ok := r.logs.(CommitTrackingLogStore)
if !ok {
return
}
if err := store.StageCommitIndex(commitIndex); err != nil {
r.logger.Error("failed to stage commit index in commit tracking log store", "index", commitIndex, "error", err)
}
}

// processRPC is called to handle an incoming RPC request. This must only be
// called from the main thread.
func (r *Raft) processRPC(rpc RPC) {
Expand Down Expand Up @@ -1535,6 +1552,11 @@ func (r *Raft) appendEntries(rpc RPC, a *AppendEntriesRequest) {
}

if n := len(newEntries); n > 0 {
// Stage the future commit index if possible
lastNewIndex := newEntries[len(newEntries)-1].Index
commitIndex := min(a.LeaderCommitIndex, lastNewIndex)
r.tryStageCommitIndex(commitIndex)

// Append the new entries
if err := r.logs.StoreLogs(newEntries); err != nil {
r.logger.Error("failed to append to logs", "error", err)
Expand Down
Loading
Loading