MCPcopy Create free account
hub / github.com/Permify/permify / WaitWithBackoff

Function WaitWithBackoff

internal/storage/postgres/utils/common.go:170–198  ·  view source on GitHub ↗

WaitWithBackoff implements an exponential backoff strategy with jitter for retries. It waits for a calculated duration or until the context is cancelled, whichever comes first.

(ctx context.Context, tenantID string, retries int)

Source from the content-addressed store, hash-verified

168// WaitWithBackoff implements an exponential backoff strategy with jitter for retries.
169// It waits for a calculated duration or until the context is cancelled, whichever comes first.
170func WaitWithBackoff(ctx context.Context, tenantID string, retries int) {
171 // Calculate the base backoff with bit shifting for better performance
172 baseBackoff := 20 * time.Millisecond
173 if retries > 0 {
174 // Use bit shifting instead of math.Pow for better performance
175 shift := min(retries, 5) // Cap at 2^5 = 32, so max backoff is 640ms
176 baseBackoff = baseBackoff << shift
177 }
178
179 // Cap at 1 second
180 if baseBackoff > time.Second {
181 baseBackoff = time.Second
182 }
183
184 // Generate jitter using crypto/rand
185 jitter := time.Duration(secureRandomFloat64() * float64(baseBackoff) * 0.5)
186 nextBackoff := baseBackoff + jitter
187
188 // Log the retry wait
189 slog.WarnContext(ctx, "waiting before retry",
190 slog.String("tenant_id", tenantID),
191 slog.Int64("backoff_duration", nextBackoff.Milliseconds()))
192
193 // Wait or exit on context cancellation
194 select {
195 case <-time.After(nextBackoff):
196 case <-ctx.Done():
197 }
198}
199
200// secureRandomFloat64 generates a float64 value in the range [0, 1) using crypto/rand.
201// Optimized version with better error handling and performance.

Callers 4

WriteMethod · 0.92
DeleteMethod · 0.92
RunBundleMethod · 0.92
common_test.goFile · 0.92

Calls 2

secureRandomFloat64Function · 0.85
StringMethod · 0.65

Tested by

no test coverage detected