Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

perf(backend): cache redundant active-subscription lookups on the billing status endpoint (#14229)

Bently3f9570713a25
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index c980d5fedb..a3ca881093 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -1702,13 +1702,12 @@ async def get_proration_credit_cents(user_id: str, monthly_cost_cents: int) -> i
if not user.stripe_customer_id:
return 0
try:
- customer_id = user.stripe_customer_id
- subscriptions = await run_in_threadpool(
- stripe.Subscription.list, customer=customer_id, status="active", limit=1
- )
- if not subscriptions.data:
+ sub = await _get_active_subscription_cached(user.stripe_customer_id)
+ # Proration only applies to a paid, active subscription — a trialing
+ # sub has no paid time to prorate. Matches the previous active-only
+ # query (status="active") while sharing the cached lookup.
+ if sub is None or sub.get("status") != "active":
return 0
- sub = subscriptions.data[0]
period_start: int = sub["current_period_start"]
period_end: int = sub["current_period_end"]
now = int(time.time())
@@ -1767,6 +1766,30 @@ async def _get_active_subscription(customer_id: str) -> stripe.Subscription | No
return None
+@cached(ttl_seconds=15, maxsize=2048, cache_none=True)
+async def _get_active_subscription_cached(
+ customer_id: str,
+) -> stripe.Subscription | None:
+ """Short-TTL per-customer cache over :func:`_get_active_subscription`.
+
+ ``get_subscription_status`` resolves the active subscription up to three
+ times in a single request (billing cycle, period end, proration), and the
+ endpoint is hit on essentially every authenticated page load (PaywallGate
+ wraps the app shell). Without a cache each of those repeats a Stripe
+ ``Subscription.list`` — the same customer's live sub fetched several times
+ per request, and again on every page view. A brief cache collapses them
+ into one lookup per customer per window.
+
+ Read-only display helpers use this. Subscription mutation flows keep calling
+ :func:`_get_active_subscription` directly so they always act on fresh Stripe
+ state; the 15-second window here only affects display fields (billing cycle,
+ next-invoice date, proration estimate), which the frontend re-fetches and
+ which self-correct well inside the tolerances already used elsewhere (the
+ pending-change lookup is cached for 30s).
+ """
+ return await _get_active_subscription(customer_id)
+
+
async def get_user_billing_cycle(user_id: str) -> BillingCycle | None:
"""Return the billing cycle ("monthly"/"yearly") of the user's active sub.
@@ -1781,7 +1804,7 @@ async def get_user_billing_cycle(user_id: str) -> BillingCycle | None:
if not user.stripe_customer_id:
return None
try:
- sub = await _get_active_subscription(user.stripe_customer_id)
+ sub = await _get_active_subscription_cached(user.stripe_customer_id)
except stripe.StripeError:
logger.warning(
"get_user_billing_cycle: Stripe lookup failed for user %s", user_id
@@ -1828,7 +1851,7 @@ async def get_active_subscription_period_end(user_id: str) -> int | None:
if not user.stripe_customer_id:
return None
try:
- sub = await _get_active_subscription(user.stripe_customer_id)
+ sub = await _get_active_subscription_cached(user.stripe_customer_id)
except stripe.StripeError:
logger.warning(
"get_active_subscription_period_end: Stripe lookup failed for user %s",
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index 26200fed49..8639f6a1ab 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -13,6 +13,7 @@ from prisma.models import User
from backend.data.credit import (
UserCredit,
+ _get_active_subscription_cached,
_is_stripe_reconcilable,
build_price_to_tier_map,
cancel_stripe_subscription,
@@ -44,6 +45,19 @@ def _clear_cache(fn: _CacheClearable) -> None:
fn.cache_clear()
[email protected](autouse=True)
+def _clear_active_subscription_cache():
+ """Isolate the short-TTL active-subscription cache between tests.
+
+ ``get_user_billing_cycle`` / ``get_active_subscription_period_end`` /
+ ``get_proration_credit_cents`` share ``_get_active_subscription_cached``;
+ clear it so a subscription mocked in one test cannot leak into the next
+ through the cache.
+ """
+ _clear_cache(_get_active_subscription_cached)
+ yield
+
+
@pytest.mark.asyncio
async def test_set_subscription_tier_updates_db():
with (
@@ -852,11 +866,10 @@ async def test_get_proration_credit_cents_with_active_sub():
period_end = now + 15 * 24 * 3600 # 15 days ahead
mock_sub = {
"id": "sub_abc",
+ "status": "active",
"current_period_start": period_start,
"current_period_end": period_end,
}
- mock_subs = MagicMock()
- mock_subs.data = [mock_sub]
with (
patch(
@@ -865,8 +878,9 @@ async def test_get_proration_credit_cents_with_active_sub():
return_value=_make_user_with_stripe("cus_123"),
),
patch(
- "backend.data.credit.stripe.Subscription.list",
- return_value=mock_subs,
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ return_value=mock_sub,
),
):
result = await get_proration_credit_cents("user-1", monthly_cost_cents=2000)
@@ -874,6 +888,47 @@ async def test_get_proration_credit_cents_with_active_sub():
assert result < 2000
+async def test_get_proration_credit_cents_trialing_sub_returns_zero():
+ """A trialing sub has no paid time to prorate — returns 0 (active-only)."""
+ mock_sub = {
+ "id": "sub_trial",
+ "status": "trialing",
+ "current_period_start": 1,
+ "current_period_end": 10_000_000_000,
+ }
+ with (
+ patch(
+ "backend.data.credit.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=_make_user_with_stripe("cus_123"),
+ ),
+ patch(
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ return_value=mock_sub,
+ ),
+ ):
+ result = await get_proration_credit_cents("user-1", monthly_cost_cents=2000)
+ assert result == 0
+
+
+async def test_active_subscription_lookup_is_cached_within_window():
+ """The subscription-status display path resolves the active sub several
+ times per request; the cached wrapper collapses those into one Stripe call."""
+ mock_sub = {"id": "sub_abc", "status": "active"}
+ with patch(
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ return_value=mock_sub,
+ ) as raw:
+ first = await _get_active_subscription_cached("cus_cache")
+ second = await _get_active_subscription_cached("cus_cache")
+ assert first is second is mock_sub
+ raw.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_create_subscription_checkout_returns_url():
mock_session = MagicMock()