This PR reduces database write amplification on the request success path and removes several hot-path writes from `accounts.extra` + `scheduler_outbox`. It also prepares dashboard endpoints to rely on pre-aggregated data instead of scanning `usage_logs` under load. The goal is to keep admin dashboard, balance update, auth refresh, and billing-related paths stable under sustained 500+ RPS traffic.
usage_5h = CASE WHEN window_5h_start IS NOT NULL AND window_5h_start + INTERVAL '5 hours' <= NOW() THEN $1 ELSE usage_5h + $1 END,
usage_1d = CASE WHEN window_1d_start IS NOT NULL AND window_1d_start + INTERVAL '24 hours' <= NOW() THEN $1 ELSE usage_1d + $1 END,
usage_7d = CASE WHEN window_7d_start IS NOT NULL AND window_7d_start + INTERVAL '7 days' <= NOW() THEN $1 ELSE usage_7d + $1 END,
window_5h_start = CASE WHEN window_5h_start IS NULL OR window_5h_start + INTERVAL '5 hours' <= NOW() THEN NOW() ELSE window_5h_start END,
window_1d_start = CASE WHEN window_1d_start IS NULL OR window_1d_start + INTERVAL '24 hours' <= NOW() THEN date_trunc('day', NOW()) ELSE window_1d_start END,
window_7d_start = CASE WHEN window_7d_start IS NULL OR window_7d_start + INTERVAL '7 days' <= NOW() THEN date_trunc('day', NOW()) ELSE window_7d_start END,
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2",requestID,apiKey.ID).Scan(&dedupCount))
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COALESCE((extra->>'quota_used')::numeric, 0) FROM accounts WHERE id = $1",account.ID).Scan("aUsed))
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1",oldRequestID).Scan(&oldCount))
require.Equal(t,0,oldCount)
varnewCountint
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1",newRequestID).Scan(&newCount))
require.Equal(t,1,newCount)
vararchivedCountint
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COUNT(*) FROM usage_billing_dedup_archive WHERE request_id = $1",oldRequestID).Scan(&archivedCount))
require.NoError(t,integrationDB.QueryRowContext(ctx,"SELECT COUNT(*) FROM usage_logs WHERE request_id = $1 AND api_key_id = $2",requestID,apiKey.ID).Scan(&count))