fix(redis): flush in-flight counts from the refresh loop

begin and end now add to a local accumulator. The refresh loop sends
all deltas in one incrMulti before each read, so a request starts no
goroutine and makes no store call. A failed flush keeps the deltas.
Deltas for epochs outside the read window are discarded.

Breaker failures use the same path. The instance whose flush takes a
count from below the threshold to at or above it opens the breaker.
The loop does not idle-stop with pending deltas and flushes on Close.
This commit is contained in:
2026-11-26 03:22:50 +00:00
parent 590a23750b
commit 807cc6ee75
2 changed files with 348 additions and 53 deletions
+179 -40
View File
@@ -34,22 +34,29 @@ type sharedPrimitive interface {
apply(vals []int64)
}
// sharedFlusher is a primitive that accumulates writes locally and sends them from the loop.
type sharedFlusher interface {
// flush writes the accumulated deltas; on error it keeps them for the next tick.
flush(l *sharedStateLoop, now time.Time) error
pending() bool
}
// sharedStateLoop refreshes every registered primitive from the store in the background, so request paths read local copies only.
type sharedStateLoop struct {
store counterStore
nowFn func() time.Time
logf func(string, ...any)
// lossy runs best-effort writes and may drop them under pressure.
lossy func(func())
// sure runs writes that must not be dropped.
sure func(func())
lossy func(func())
lastUse time.Time
stop chan struct{}
done chan struct{}
prims []sharedPrimitive
flushers []sharedFlusher
every time.Duration
failures int
mu sync.Mutex
flushMu sync.Mutex
running bool
closed bool
}
@@ -60,18 +67,17 @@ func newSharedStateLoop(store counterStore, lossy func(func()), logf func(string
logf = func(string, ...any) {}
}
l := &sharedStateLoop{store: store, nowFn: time.Now, logf: logf, lossy: lossy, every: sharedStateRefreshInterval}
l.sure = func(f func()) {
go func() { //nolint:gosec // G118: in-flight writes must never drop; bounded by request concurrency
defer func() {
if rec := recover(); rec != nil {
logf("shared state write panicked: %v", rec)
}
}()
f()
}()
}
if l.lossy == nil {
l.lossy = l.sure
l.lossy = func(f func()) {
go func() { //nolint:gosec // G118: best-effort write; bounded by the caller's request rate
defer func() {
if rec := recover(); rec != nil {
logf("shared state write panicked: %v", rec)
}
}()
f()
}()
}
}
return l
}
@@ -81,6 +87,39 @@ func (l *sharedStateLoop) log(format string, args ...any) {
l.logf(format, args...)
}
func (l *sharedStateLoop) registerFlusher(f sharedFlusher) {
l.mu.Lock()
l.flushers = append(l.flushers, f)
l.mu.Unlock()
}
// flush sends every flusher's accumulated deltas. A failed flusher keeps its deltas for the next call.
func (l *sharedStateLoop) flush() {
// One flush at a time: concurrent ones would send the same deltas twice.
l.flushMu.Lock()
defer l.flushMu.Unlock()
l.mu.Lock()
fl := make([]sharedFlusher, len(l.flushers))
copy(fl, l.flushers)
l.mu.Unlock()
now := l.nowFn()
for _, f := range fl {
if err := f.flush(l, now); err != nil {
l.log("shared state flush failed: %v", err)
}
}
}
// hasPending reports whether any flusher holds unsent deltas. The caller holds l.mu.
func (l *sharedStateLoop) hasPending() bool {
for _, f := range l.flushers {
if f.pending() {
return true
}
}
return false
}
func (l *sharedStateLoop) register(p sharedPrimitive) {
l.mu.Lock()
l.prims = append(l.prims, p)
@@ -134,7 +173,7 @@ func (l *sharedStateLoop) run(stop, done chan struct{}) {
return
case <-t.C:
l.mu.Lock()
idle := l.nowFn().Sub(l.lastUse) > sharedStateIdleStop
idle := l.nowFn().Sub(l.lastUse) > sharedStateIdleStop && !l.hasPending()
if idle {
l.running = false
}
@@ -154,12 +193,13 @@ func (l *sharedStateLoop) close() {
return
}
l.mu.Lock()
defer l.mu.Unlock()
l.closed = true
if l.running {
l.running = false
close(l.stop)
}
l.mu.Unlock()
l.flush()
}
func (l *sharedStateLoop) snapshot() []sharedPrimitive {
@@ -177,8 +217,9 @@ func (l *sharedStateLoop) clearAll() {
}
}
// refresh reads every primitive's keys in chunked getMulti calls and hands each its values.
// refresh flushes pending deltas, then reads every primitive's keys in chunked getMulti calls and hands each its values.
func (l *sharedStateLoop) refresh() {
l.flush()
prims := l.snapshot()
now := l.nowFn()
var all []string
@@ -283,6 +324,7 @@ type sharedBreaker struct {
local map[string]*breakerLocal
openUntil map[string]int64
failsSeen map[string]int64
failAcc map[string]int64
kind string
ids []string
openBase time.Duration
@@ -297,11 +339,12 @@ func newSharedBreaker(loop *sharedStateLoop, kind string, ids []string, threshol
b := &sharedBreaker{
loop: loop, nowFn: time.Now, kind: kind, ids: ids,
threshold: threshold, openBase: openBase, openMax: openMax, failWindow: failWindow,
local: make(map[string]*breakerLocal), openUntil: make(map[string]int64), failsSeen: make(map[string]int64),
local: make(map[string]*breakerLocal), openUntil: make(map[string]int64), failsSeen: make(map[string]int64), failAcc: make(map[string]int64),
}
if loop != nil {
b.nowFn = loop.nowFn
loop.register(b)
loop.registerFlusher(b)
}
return b
}
@@ -350,16 +393,15 @@ func (b *sharedBreaker) isOpen(id string) bool {
return b.openUntil[id] > now.UnixMilli()
}
// recordFailure updates local state and, in the background, the shared failure count.
// recordFailure updates local state and queues the failure for the loop to flush.
func (b *sharedBreaker) recordFailure(id string) {
b.mu.Lock()
b.recordFailureLocal(b.localFor(id), b.nowFn())
b.mu.Unlock()
if b.loop == nil {
return
if b.loop != nil {
b.failAcc[id]++
}
b.mu.Unlock()
b.loop.touch()
b.loop.lossy(func() { b.shareFailure(id) })
}
// recordFailureLocal is requestHealthTracker.record's failure arm with this breaker's tunables.
@@ -387,13 +429,55 @@ func (b *sharedBreaker) recordFailureLocal(st *breakerLocal, now time.Time) {
}
}
// shareFailure counts one failure fleet-wide; only the instance that reaches the threshold opens the breaker.
func (b *sharedBreaker) shareFailure(id string) {
l := b.loop
fails, ok := l.incrAndGet(counterIncr{key: sharedBreakerKey(b.kind, id, "fails"), delta: 1, ttl: b.failWindow, enforceTTL: b.failWindow})
if !ok || fails != int64(b.threshold) {
return
func (b *sharedBreaker) pending() bool {
b.mu.Lock()
defer b.mu.Unlock()
return len(b.failAcc) > 0
}
// flush adds the queued failures to the fleet counts. The instance whose flush takes a count from below the
// threshold to at or above it is the single opener.
func (b *sharedBreaker) flush(l *sharedStateLoop, _ time.Time) error {
b.mu.Lock()
ids := make([]string, 0, len(b.failAcc))
deltas := make([]int64, 0, len(b.failAcc))
for id, n := range b.failAcc {
ids = append(ids, id)
deltas = append(deltas, n)
}
b.mu.Unlock()
if len(ids) == 0 {
return nil
}
entries := make([]counterIncr, len(ids))
for i, id := range ids {
entries[i] = counterIncr{key: sharedBreakerKey(b.kind, id, "fails"), delta: deltas[i], ttl: b.failWindow, enforceTTL: b.failWindow}
}
post, _, err := l.store.incrAndGetMulti(entries, nil)
if err != nil {
return err
}
if len(post) != len(ids) {
return nil
}
b.mu.Lock()
for i, id := range ids {
if left := b.failAcc[id] - deltas[i]; left > 0 {
b.failAcc[id] = left
} else {
delete(b.failAcc, id)
}
}
b.mu.Unlock()
for i, id := range ids {
if post[i]-deltas[i] < int64(b.threshold) && post[i] >= int64(b.threshold) {
b.trip(l, id)
}
}
return nil
}
func (b *sharedBreaker) trip(l *sharedStateLoop, id string) {
opensTTL := b.openMax * sharedBreakerOpensTTLFactor
opens, ok := l.incrAndGet(counterIncr{key: sharedBreakerKey(b.kind, id, "opens"), delta: 1, ttl: opensTTL, enforceTTL: opensTTL})
if !ok {
@@ -428,6 +512,7 @@ func (b *sharedBreaker) recordSuccess(id string) {
b.mu.Lock()
st := b.localFor(id)
dirty := st.consecutiveFailures > 0 || b.failsSeen[id] > 0
delete(b.failAcc, id)
st.open = false
st.consecutiveFailures = 0
st.backoff = 0
@@ -445,12 +530,20 @@ func (b *sharedBreaker) recordSuccess(id string) {
b.mu.Unlock()
}
// infDelta is one counter's unflushed increment.
type infDelta struct {
key string
epoch int64
n int64
}
// sharedInflight counts in-flight requests per provider fleet-wide with epoch-bucketed started/finished counters, so a crashed pod's leak ages out.
type sharedInflight struct {
loop *sharedStateLoop
nowFn func() time.Time
counts map[string]int
limits map[string]int
acc map[string]*infDelta
ids []string
epochs int
mu sync.Mutex
@@ -462,10 +555,11 @@ func newSharedInflight(loop *sharedStateLoop, ids []string, maxRequestTimeout ti
if m < 1 {
m = 1
}
s := &sharedInflight{loop: loop, nowFn: time.Now, ids: ids, epochs: m, counts: make(map[string]int), limits: make(map[string]int)}
s := &sharedInflight{loop: loop, nowFn: time.Now, ids: ids, epochs: m, counts: make(map[string]int), limits: make(map[string]int), acc: make(map[string]*infDelta)}
if loop != nil {
s.nowFn = loop.nowFn
loop.register(s)
loop.registerFlusher(s)
}
return s
}
@@ -517,27 +611,72 @@ func (s *sharedInflight) apply(vals []int64) {
}
}
// begin records a started request and returns the func that records its end, once. Writes are never dropped.
// begin records a started request and returns the func that records its end, once.
// It only adds to a local accumulator; the loop flushes it.
func (s *sharedInflight) begin(provider string) func() {
if s.loop == nil {
return func() {}
}
s.loop.touch()
epoch := s.epochOf(s.nowFn())
ttl := s.ttl()
s.loop.sure(func() {
s.loop.write([]counterIncr{{key: s.epochKey(provider, epoch, "s"), delta: 1, ttl: ttl, enforceTTL: ttl}})
})
s.add(provider, epoch, "s")
var once sync.Once
return func() {
once.Do(func() {
s.loop.sure(func() {
s.loop.write([]counterIncr{{key: s.epochKey(provider, epoch, "f"), delta: 1, ttl: ttl, enforceTTL: ttl}})
})
})
once.Do(func() { s.add(provider, epoch, "f") })
}
}
func (s *sharedInflight) add(provider string, epoch int64, kind string) {
key := s.epochKey(provider, epoch, kind)
s.mu.Lock()
d, ok := s.acc[key]
if !ok {
d = &infDelta{key: key, epoch: epoch}
s.acc[key] = d
}
d.n++
s.mu.Unlock()
}
func (s *sharedInflight) pending() bool {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.acc) > 0
}
// flush writes every non-zero delta in one incrMulti. Epochs outside the read window are discarded.
// On error the deltas stay and later begin/end calls add on top of them.
func (s *sharedInflight) flush(l *sharedStateLoop, now time.Time) error {
oldest := s.epochOf(now) - int64(s.epochs)
s.mu.Lock()
entries := make([]counterIncr, 0, len(s.acc))
for k, d := range s.acc {
if d.epoch <= oldest {
delete(s.acc, k)
} else if d.n > 0 {
entries = append(entries, counterIncr{key: d.key, delta: d.n, ttl: s.ttl(), enforceTTL: s.ttl()})
}
}
s.mu.Unlock()
if len(entries) == 0 {
return nil
}
if _, err := l.store.incrMulti(entries); err != nil {
return err
}
s.mu.Lock()
for _, e := range entries {
if d, ok := s.acc[e.key]; ok {
d.n -= e.delta
if d.n <= 0 {
delete(s.acc, e.key)
}
}
}
s.mu.Unlock()
return nil
}
// shared returns the fleet-wide in-flight count from the last refresh.
func (s *sharedInflight) shared(provider string) int {
s.loop.touch()
+169 -13
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"net/http"
"runtime"
"strings"
"sync"
"testing"
@@ -30,10 +31,11 @@ func (c *sharedClock) advance(d time.Duration) {
// sharedRecStore wraps a counterStore, logging every key touched and optionally failing reads.
type sharedRecStore struct {
counterStore
failGet error
reads []string
writes []counterIncr
mu sync.Mutex
failGet error
failIncr error
reads []string
writes []counterIncr
mu sync.Mutex
}
func (r *sharedRecStore) getMulti(keys []string) ([]int64, error) {
@@ -49,6 +51,11 @@ func (r *sharedRecStore) getMulti(keys []string) ([]int64, error) {
func (r *sharedRecStore) incrMulti(e []counterIncr) ([]int64, error) {
r.mu.Lock()
if r.failIncr != nil {
err := r.failIncr
r.mu.Unlock()
return nil, err
}
r.writes = append(r.writes, e...)
r.mu.Unlock()
return r.counterStore.incrMulti(e)
@@ -56,6 +63,11 @@ func (r *sharedRecStore) incrMulti(e []counterIncr) ([]int64, error) {
func (r *sharedRecStore) incrAndGetMulti(e []counterIncr, reads []string) ([]int64, []int64, error) {
r.mu.Lock()
if r.failIncr != nil {
err := r.failIncr
r.mu.Unlock()
return nil, nil, err
}
r.writes = append(r.writes, e...)
r.mu.Unlock()
return r.counterStore.incrAndGetMulti(e, reads)
@@ -73,6 +85,12 @@ func (r *sharedRecStore) writesTo(suffix string) int {
return n
}
func (r *sharedRecStore) setFailIncr(err error) {
r.mu.Lock()
r.failIncr = err
r.mu.Unlock()
}
func (r *sharedRecStore) setFail(err error) {
r.mu.Lock()
r.failGet = err
@@ -91,7 +109,7 @@ func sharedTestLoop(store counterStore, clk *sharedClock) *sharedStateLoop {
l := newSharedStateLoop(store, nil, nil)
l.nowFn = clk.now
sync := func(f func()) { f() }
l.lossy, l.sure = sync, sync
l.lossy = sync
// Tests drive refresh by hand; closed keeps touch from starting the goroutine.
l.closed = true
return l
@@ -114,11 +132,13 @@ func TestSharedBreakerTripsFleetWide(t *testing.T) {
a.recordFailure("p")
a.recordFailure("p")
la.refresh()
lc.refresh()
if c.isOpen("p") {
t.Fatal("C open after 2 fleet failures, want closed")
}
b.recordFailure("p")
lb.refresh()
if c.isOpen("p") {
t.Fatal("C open before refresh, isOpen must not read the store")
}
@@ -136,9 +156,15 @@ func TestSharedBreakerOnlyOneOpener(t *testing.T) {
store, clk := sharedTestEnv()
loops := []*sharedStateLoop{sharedTestLoop(store, clk), sharedTestLoop(store, clk)}
brks := []*sharedBreaker{testBreaker(loops[0]), testBreaker(loops[1])}
for i := 0; i < 5; i++ {
brks[i%2].recordFailure("p")
}
// A flushes 2 (0 to 2), B flushes 2 (2 to 4, crosses 3), A flushes 1 more (reset after the trip, 1 to 2).
brks[0].recordFailure("p")
brks[0].recordFailure("p")
loops[0].refresh()
brks[1].recordFailure("p")
brks[1].recordFailure("p")
loops[1].refresh()
brks[0].recordFailure("p")
loops[0].refresh()
if got := store.writesTo(":open"); got != 1 {
t.Errorf("writes to open = %d, want 1", got)
}
@@ -154,6 +180,7 @@ func TestSharedBreakerSuccessResets(t *testing.T) {
a.recordFailure("p")
a.recordFailure("p")
la.refresh()
lb.refresh()
b.recordSuccess("p")
// A's own local count stays; the fleet count is what C reads.
@@ -161,11 +188,13 @@ func TestSharedBreakerSuccessResets(t *testing.T) {
a2 := testBreaker(sharedTestLoop(store, clk))
a2.recordFailure("p")
a2.recordFailure("p")
a2.loop.refresh()
lc.refresh()
if c.isOpen("p") {
t.Fatal("C open after success reset then 2 failures, want closed")
}
a2.recordFailure("p")
a2.loop.refresh()
lc.refresh()
if !c.isOpen("p") {
t.Fatal("C closed after 3 failures since the reset, want open")
@@ -198,6 +227,7 @@ func TestSharedBreakerBackoffDoubles(t *testing.T) {
for i := 0; i < 3; i++ {
b.recordFailure("p")
}
l.refresh()
}
want := []time.Duration{testBrkOpenBase, 2 * testBrkOpenBase, 4 * testBrkOpenBase, 8 * testBrkOpenBase, testBrkOpenMax, testBrkOpenMax}
for i, w := range want {
@@ -260,19 +290,25 @@ func inflightEnv(maxReq time.Duration) (*sharedRecStore, *sharedClock, func() (*
}
func TestSharedInflightSums(t *testing.T) {
_, _, mk := inflightEnv(10 * time.Minute)
_, a := mk()
_, b := mk()
store, _, mk := inflightEnv(10 * time.Minute)
la, a := mk()
lb, b := mk()
lc, c := mk()
end1 := a.begin("p")
a.begin("p")
b.begin("p")
if got := store.writesTo(":s"); got != 0 {
t.Fatalf("begin wrote %d entries before a flush, want 0", got)
}
la.refresh()
lb.refresh()
lc.refresh()
if got := c.shared("p"); got != 3 {
t.Fatalf("shared = %d, want 3", got)
}
end1()
end1() // a second end must not double-count
la.refresh()
lc.refresh()
if got := c.shared("p"); got != 2 {
t.Fatalf("shared after one end = %d, want 2", got)
@@ -287,9 +323,10 @@ func TestSharedInflightSums(t *testing.T) {
func TestSharedInflightCrashLeakExpires(t *testing.T) {
_, clk, mk := inflightEnv(10 * time.Minute)
_, a := mk()
la, a := mk()
lc, c := mk()
a.begin("p") // never ended: the pod crashed
la.refresh()
lc.refresh()
if got := c.shared("p"); got != 1 {
t.Fatalf("shared = %d, want 1", got)
@@ -303,11 +340,13 @@ func TestSharedInflightCrashLeakExpires(t *testing.T) {
func TestSharedInflightEndInLaterEpochCreditsStartEpoch(t *testing.T) {
_, clk, mk := inflightEnv(10 * time.Minute)
_, a := mk()
la, a := mk()
lc, c := mk()
end := a.begin("p")
la.refresh()
clk.advance(sharedInflightEpoch + time.Second)
end()
la.refresh()
lc.refresh()
if got := c.shared("p"); got != 0 {
t.Fatalf("shared = %d, want 0 (end credited to the start epoch)", got)
@@ -359,6 +398,7 @@ func TestSharedStateStoreErrorFallsBackLocal(t *testing.T) {
for i := 0; i < 3; i++ {
a.recordFailure("p")
}
la.refresh()
lc.refresh()
if !c.isOpen("p") {
t.Fatal("setup: C should see the shared open")
@@ -581,3 +621,119 @@ func TestSharedStateIDs(t *testing.T) {
t.Errorf("ids = %q, want a,b,c", got)
}
}
func TestSharedInflightFlushErrorRetains(t *testing.T) {
store, _, mk := inflightEnv(10 * time.Minute)
la, a := mk()
lc, c := mk()
end := a.begin("p")
a.begin("p")
a.begin("p")
end()
store.setFailIncr(errors.New("redis down"))
la.refresh()
a.begin("p") // lands on top of the retained deltas
la.refresh()
lc.refresh()
if got := c.shared("p"); got != 0 {
t.Fatalf("shared during outage = %d, want 0", got)
}
store.setFailIncr(nil)
la.refresh()
lc.refresh()
if got := c.shared("p"); got != 3 {
t.Fatalf("shared after recovery = %d, want 3 (4 started, 1 finished)", got)
}
if got := store.writesTo(":s"); got != 1 {
t.Errorf("start-counter writes = %d, want 1 summed delta", got)
}
for _, w := range store.writes {
if strings.HasSuffix(w.key, ":s") && w.delta != 4 {
t.Errorf("start delta = %d, want 4", w.delta)
}
}
la.refresh()
if got := store.writesTo(":s"); got != 1 {
t.Errorf("a flushed delta was written again: %d writes", got)
}
}
func TestSharedInflightDropsDeadEpochDeltas(t *testing.T) {
store, clk, mk := inflightEnv(10 * time.Minute)
la, a := mk()
a.begin("p")
store.setFailIncr(errors.New("redis down"))
clk.advance(time.Duration(a.epochs+1) * sharedInflightEpoch)
la.refresh()
store.setFailIncr(nil)
la.refresh()
if got := store.writesTo(":s"); got != 0 {
t.Errorf("wrote %d counters for an epoch past its TTL, want 0", got)
}
a.mu.Lock()
n := len(a.acc)
a.mu.Unlock()
if n != 0 {
t.Errorf("accumulator holds %d dead entries", n)
}
}
func TestSharedInflightNoGoroutinePerRequest(t *testing.T) {
store, _, mk := inflightEnv(10 * time.Minute)
_, a := mk()
before := runtime.NumGoroutine()
for i := 0; i < 1000; i++ {
a.begin("p")()
}
if after := runtime.NumGoroutine(); after > before+1 {
t.Errorf("goroutines %d -> %d across 1000 begin/end", before, after)
}
if len(store.writes) != 0 {
t.Errorf("begin/end wrote %d entries to the store, want 0", len(store.writes))
}
}
func TestSharedStateCloseFlushes(t *testing.T) {
store, clk := sharedTestEnv()
l := newSharedStateLoop(store, nil, nil)
l.nowFn = clk.now
l.every = time.Hour
in := newSharedInflight(l, []string{"p"}, time.Minute)
b := testBreaker(l)
b.recordFailure("p")
in.begin("p")
l.close()
if got := store.writesTo(":s"); got != 1 {
t.Errorf("close flushed %d in-flight writes, want 1", got)
}
if got := store.writesTo(":fails"); got != 1 {
t.Errorf("close flushed %d failure writes, want 1", got)
}
}
func TestSharedStateNoIdleStopWithPendingDeltas(t *testing.T) {
store, clk := sharedTestEnv()
l := newSharedStateLoop(store, nil, nil)
l.nowFn = clk.now
l.every = 5 * time.Millisecond
in := newSharedInflight(l, []string{"p"}, 20*time.Minute)
store.setFailIncr(errors.New("redis down"))
in.begin("p")
clk.advance(sharedStateIdleStop + time.Second)
time.Sleep(50 * time.Millisecond)
l.mu.Lock()
running := l.running
l.mu.Unlock()
if !running {
t.Fatal("loop idle-stopped with unflushed deltas")
}
store.setFailIncr(nil)
deadline := time.Now().Add(2 * time.Second)
for store.writesTo(":s") == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if store.writesTo(":s") != 1 {
t.Error("pending delta never flushed")
}
l.close()
}