Cache SubscriptionSettings + cut monitoring poll noise
Backend CI / Test (push) Has been cancelled
Backend CI / Contract Tests (push) Has been cancelled
Backend CI / Build (push) Has been cancelled
Backend CI / Lint (push) Has been cancelled
Backend CI / Secret Scanning (push) Has been cancelled

Trace data revealed subscription_subscriptionsettings was consuming
1,983s of cumulative DB time per day (180× more than the next-largest
table) for a 32-byte singleton row of admin-toggleable global flags.
Root cause was a 30-second poll loop in monitoring.Service per pod
plus uncached reads on every authed status check / CreateResidence /
Stripe webhook. Fix is layered:

1. Redis cache for SubscriptionSettings — same shape as the
   residence-IDs cache. 30-min TTL, explicit invalidation on admin
   write. New CacheService.{Cache,GetCached,Invalidate}SubscriptionSettings
   plus a cachedSubscriptionSettings helper in services/.

2. SubscriptionService, StripeService, and both admin handlers
   (settings + limitations) now read through the cache. Admin write
   handlers invalidate so toggles propagate cluster-wide within ms
   instead of waiting for the TTL.

3. monitoring.Service.syncSettingsFromDB also reads from Redis first
   (raw redis.Client to avoid a services→monitoring import cycle).
   Polling interval bumped 30s → 5min. Combined with Redis-shared
   cache, cluster-wide DB hits from this poll go from ~480/hour to
   ~2/hour — a 240× reduction.

4. StripeService.CreateCheckoutSession now takes ctx so the cached
   settings span (and the Stripe webhook trace) stay attached to the
   request. Handler call site updated.

5. Admin handlers' direct h.db.First calls switched to
   db.WithContext(ctx) so the resulting orphan SQL spans nest under
   the admin request span in Jaeger.

Net DB query rate for subscription_subscriptionsettings should drop
from 0.101/sec to ~0/sec with occasional invalidation-driven refills,
and the table's cumulative DB time from 1,983s/day to ~10s/day.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-04-26 21:29:30 -05:00
parent c9ac273dbd
commit b67f7f9e6b
10 changed files with 240 additions and 32 deletions
+49
View File
@@ -446,3 +446,52 @@ func (c *CacheService) InvalidateResidenceIDsForUsers(ctx context.Context, userI
}
return c.Delete(ctx, keys...)
}
// === SubscriptionSettings cache ===
//
// SubscriptionSettings is a 32-byte singleton row of admin-toggleable global
// flags (EnableLimitations, EnableMonitoring, TrialEnabled, TrialDurationDays).
// Read on every authed status check, every CreateResidence, and once per
// 30s by every monitoring goroutine. Cached forever-ish here; admin writes
// invalidate explicitly.
//
// 30-minute TTL is belt-and-suspenders against an admin update that somehow
// bypasses the invalidation path (e.g., a manual SQL UPDATE). The flag value
// converging within 30 min is fine for any real use case.
const (
subscriptionSettingsKey = "subscription_settings:1"
subscriptionSettingsTTL = 30 * time.Minute
)
// CacheSubscriptionSettings stores the singleton settings row. Caller passes
// any encodable value — typically *models.SubscriptionSettings. Best-effort.
func (c *CacheService) CacheSubscriptionSettings(ctx context.Context, settings interface{}) error {
if c == nil {
return nil
}
data, err := json.Marshal(settings)
if err != nil {
return err
}
return c.client.Set(ctx, subscriptionSettingsKey, data, subscriptionSettingsTTL).Err()
}
// GetCachedSubscriptionSettings unmarshals into the supplied destination.
// Returns redis.Nil on cache miss so callers can distinguish from genuine errors.
func (c *CacheService) GetCachedSubscriptionSettings(ctx context.Context, dest interface{}) error {
if c == nil {
return fmt.Errorf("cache not available")
}
return c.Get(ctx, subscriptionSettingsKey, dest)
}
// InvalidateSubscriptionSettings drops the singleton-settings cache. Called
// from admin handlers that update the row so the new values are visible
// immediately to all pods (instead of waiting for the 30-min TTL).
func (c *CacheService) InvalidateSubscriptionSettings(ctx context.Context) error {
if c == nil {
return nil
}
return c.Delete(ctx, subscriptionSettingsKey)
}