Skip to content

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

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

Open
wants to merge 38 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
38 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
3a5d299
Merge branch 'main' into feat/commit-tracking-log-store-checker
peterxcli Mar 27, 2025
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
30 changes: 30 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ type Raft struct {
// preVoteDisabled control if the pre-vote feature is activated,
// prevote feature is disabled if set to true.
preVoteDisabled bool

// fastRecovery is used to enable fast recovery mode
// fast recovery mode is disabled if set to false.
fastRecovery bool
}

// BootstrapCluster initializes a server's storage with the given cluster
Expand Down Expand Up @@ -566,6 +570,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,
fastRecovery: conf.FastRecovery,
}
if !transportSupportPreVote && !conf.PreVoteDisabled {
r.logger.Warn("pre-vote is disabled because it is not supported by the Transport")
Expand Down Expand Up @@ -606,6 +611,8 @@ func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps Sna
// to be called concurrently with a blocking RPC.
trans.SetHeartbeatHandler(r.processHeartbeat)

r.recoverFromCommitedLogs()

if conf.skipStartup {
return r, nil
}
Expand Down Expand Up @@ -697,6 +704,29 @@ func (r *Raft) tryRestoreSingleSnapshot(snapshot *SnapshotMeta) bool {
return true
}

// recoverFromCommitedLogs recovers the Raft node from committed logs.
func (r *Raft) recoverFromCommitedLogs() error {
if !r.fastRecovery {
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 {
return nil
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
return nil
r.logger.Debug("fast recovery enabled but log store does not support it", "log_store", fmt.Sprintf("%T", r.logs))
return nil

I'm worried about the case where someone opts into fast recovery but never actually gets to use it because their log store doesn't support it. Even for uses like mine (Nomad) where the logstore is hardcoded, reducing this to a programming error not a runtime misconfiguration, I don't see how I could observe whether our implementation was using the fast recovery path or not.

Copy link
Member

Choose a reason for hiding this comment

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

👍 I missed that this was DEBUG I think it should be a WARN.

Copy link
Author

Choose a reason for hiding this comment

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

thanks!

}
commitIndex, err := store.GetCommitIndex()
if err != nil {
return fmt.Errorf("failed to read commit index from store: %w", err)
}
if commitIndex == 0 {
return nil
}

r.processLogs(commitIndex, nil)
return nil
}

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

// FastRecovery controls if the Raft server should use the fast recovery
// mechanism. This mechanism allows a server to apply logs to the FSM till
// the last committed log
FastRecovery bool
Copy link
Member

Choose a reason for hiding this comment

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

Not sure if this is a naming nitpick or just a question:

From the perspective of a caller to NewRaft, FastRecovery might be considerably slower right? Because it blocks while replaying all locally-persisted committed logs?

IIUC the "fast" aspect is due to more logs being replayed locally instead of streamed from a peer. Logs committed while this member was down will need to be streamed, but presumably that's often a fraction of the total log size.

If my understanding is accurate, an alternative name might be CommittedLogRecovery (or even LocalCommittedLogRecovery which is even worse!), but .... Fast Recovery definitely sounds better! So I'm more curious if my reasoning is correct than suggesting we change the name.

Copy link
Member

Choose a reason for hiding this comment

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

This is great point actually. I'm not sure "Fast" does capture the semantics in any case really: mostly startup will take marginally to a lot longer, but on the plus side the FSM will actually startup in the same state it was before the node restarted which is probably what most users of the library assumed was the case already!

If my understanding is accurate

Yeah I think you perfectly described the tradeoff. I think CommittedLogRecovery is a reasonable name for the thing and we can explain the semantics in the comments.

Copy link
Author

Choose a reason for hiding this comment

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

@schmichael @banks How about RecoveryCommitted?

Copy link
Member

@schmichael schmichael Oct 10, 2024

Choose a reason for hiding this comment

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

Naming is the worst. 😅 Looking around a bit we're not totally consistent, but I think generally:

  1. Recovery refers to remediating a failure of some kind (RecoverCluster and many comments)
  2. Restore is the term used for this process: replaying logs on startup.

So I think switching Recovery -> Restore is appropriate.

After that I think I prefer RestoreCommittedLogs a tiny bit over RestoreCommitted since Committed alone is a bit ambiguous. I would accept either though!


// skipStartup allows NewRaft() to bypass all background work goroutines
skipStartup bool
}
Expand Down
28 changes: 28 additions & 0 deletions inmem_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,31 @@ func (i *InmemStore) GetUint64(key []byte) (uint64, error) {
defer i.l.RUnlock()
return i.kvInt[string(key)], nil
}

type InmemCommitTrackingStore struct {
*InmemStore
commitIndexLock sync.RWMutex
commitIndex 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) SetCommitIndex(index uint64) error {
i.commitIndexLock.Lock()
defer i.commitIndexLock.Unlock()
i.commitIndex = index
return nil
}

func (i *InmemCommitTrackingStore) GetCommitIndex() (uint64, error) {
i.commitIndexLock.RLock()
defer i.commitIndexLock.RUnlock()
return i.commitIndex, nil
}
5 changes: 5 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,8 @@ func emitLogStoreMetrics(s LogStore, prefix []string, interval time.Duration, st
}
}
}

type CommitTrackingLogStore interface {
SetCommitIndex(idx uint64) error
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.

}
16 changes: 16 additions & 0 deletions raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,8 @@ func (r *Raft) processLogs(index uint64, futures map[uint64]*logFuture) {
applyBatch(batch)
}

r.persistCommitIndex(index)

// Update the lastApplied index and term
r.setLastApplied(index)
}
Expand Down Expand Up @@ -1385,6 +1387,20 @@ func (r *Raft) prepareLog(l *Log, future *logFuture) *commitTuple {
return nil
}

// persistCommitIndex updates the commit index in persist store if fast recovery is enabled.
func (r *Raft) persistCommitIndex(index uint64) {
if !r.fastRecovery {
return
}
store, ok := r.logs.(CommitTrackingLogStore)
if !ok {
return
}
if err := store.SetCommitIndex(index); err != nil {
r.logger.Error("failed to set commit index in commit tracking log store", "index", index, "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