:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): cut Stripe per-customer API call volume (#66031)
Tom Owersb37837a0cb3d
diff --git a/posthog/temporal/tests/data_imports/conftest.py b/posthog/temporal/tests/data_imports/conftest.pyindex d5035ca04348..d01dccc41713 100644--- a/posthog/temporal/tests/data_imports/conftest.py+++ b/posthog/temporal/tests/data_imports/conftest.py@@ -408,7 +408,7 @@ def stripe_customer():"id": "cus_NffrFeUfNV2Hib","object": "customer","address": null,- "balance": 0,+ "balance": -1000,"created": 1680893993,"currency": null,"default_source": null,diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.pyindex bbb6a92aad25..533229db3506 100644--- a/posthog/temporal/tests/data_imports/test_end_to_end.py+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py@@ -3584,7 +3584,7 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cli"tax_exempt": "none","address": None,"invoice_prefix": "0759376C",- "balance": 0,+ "balance": -1000,"currency": None,"livemode": False,"invoice_settings": '{"custom_fields":null,"default_payment_method":null,"footer":null,"rendering_options":null}',diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.pyindex 3abf7090222e..621e193cb67c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py@@ -51,7 +51,12 @@ RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {REFUND_RESOURCE_NAME: "refund",SUBSCRIPTION_RESOURCE_NAME: "customer.subscription",CREDIT_NOTE_RESOURCE_NAME: "credit_note",- CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: "billing",+ # CustomerBalanceTransaction (the legacy customer credit-balance ledger returned by+ # `customers.balance_transactions.list`) has no Stripe webhook event — no event ever carries a+ # `customer_balance_transaction` object. The previous "billing" prefix only subscribed the source+ # webhook to unrelated `billing.*` events (credit grants, meters, alerts, and the distinct+ # `billing.credit_balance_transaction` object), none of which can populate this table. So it's+ # intentionally absent here and stays API-sweep-only.CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",COUPON_RESOURCE_NAME: "coupon",DISCOUNT_RESOURCE_NAME: "customer.discount",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.pyindex 114aff912c9e..0ff693e58780 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py@@ -148,6 +148,27 @@ class StripeNestedResource:parent: StripeResourceparent_name: str = ""params: dict[str, Any] = dataclasses.field(default_factory=dict)+ # Optional predicate over a parent object. When set and it returns False, we skip the nested+ # API call for that parent entirely. Stripe has no top-level list for these nested resources, so+ # the default behaviour fans out one call per parent — most of which return nothing. A cheap+ # signal already present on the parent object lets us avoid the calls that can't yield data.+ parent_has_nested: Optional[Callable[[dict[str, Any]], bool]] = None+++def _customer_might_have_balance_transactions(customer: dict[str, Any]) -> bool:+ """Skip the per-customer balance-transactions call when the customer's credit balance is exactly 0.++ A customer balance transaction is a credit/debit against the customer's stored balance, so any+ customer that has ever had one and not netted it back to zero carries a non-zero ``balance``. The+ vast majority of customers never touch their balance, so this turns the full per-customer sweep+ (one call each, almost all empty) into a handful of calls.++ Tradeoff: a customer whose balance was credited and then fully consumed back to 0 has ledger+ entries but a 0 balance, so we won't fetch their history. This is rare and an accepted cost of+ avoiding the per-customer fan-out. A missing ``balance`` (unexpected payload shape) is treated as+ "might have" so we never silently drop data."""+ balance = customer.get("balance")+ return balance is None or balance != 0@dataclasses.dataclass@@ -205,6 +226,7 @@ def _build_resources(parent_id="id",parent=StripeResource(method=client.customers.list),parent_name=CUSTOMER_RESOURCE_NAME,+ parent_has_nested=_customer_might_have_balance_transactions,),CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: StripeNestedResource(method=client.customers.payment_methods.list,@@ -276,8 +298,14 @@ def get_rows(resource.parent.method,params={**default_params, **resource.parent.params, **resume_params},)+ skipped_parents = 0for obj in stripe_parent_objects.auto_paging_iter():parent_obj_id = obj[resource.parent_id]+ # Skip parents that a cheap signal on the parent object rules out — avoids one empty+ # nested call per parent (the bulk of Stripe API volume for these resources).+ if resource.parent_has_nested is not None and not resource.parent_has_nested(obj):+ skipped_parents += 1+ continuetry:stripe_nested_objects = _call_stripe(resource.method,@@ -305,6 +333,10 @@ def get_rows(if not _is_stripe_resource_missing_error(e):raiselogger.debug(f"Stripe: skipping {resource.nested_parent_param}={parent_obj_id}, no longer exists")+ if skipped_parents:+ logger.debug(+ f"Stripe: skipped {skipped_parents} {resource.nested_parent_param}(s) with no nested data, saving that many API calls"+ )else:stripe_objects = _call_stripe(resource.method, params={**default_params, **resource.params, **resume_params}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.pyindex bf3cb8253ae7..fe6c61898132 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py@@ -11,13 +11,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.stripe import stripe as stripe_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,+ RESOURCE_TO_STRIPE_WEBHOOK_EVENT,)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (StripeAuthenticationError,StripeNestedResource,StripeResource,+ _all_known_webhook_events,get_rows,)@@ -109,16 +112,17 @@ class TestStripeSource:assert message.startswith("Stripe rejected the API key.")-def _run_nested_get_rows(nested_method):- parent = StripeResource(- method=lambda **kwargs: _list_object([{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}])- )+def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None):+ if parent_objects is None:+ parent_objects = [{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}]+ parent = StripeResource(method=lambda **kwargs: _list_object(parent_objects))resource = StripeNestedResource(method=nested_method,nested_parent_param="customer",parent_id="id",parent=parent,parent_name=CUSTOMER_RESOURCE_NAME,+ parent_has_nested=parent_has_nested,)resumable_source_manager = MagicMock()@@ -165,3 +169,58 @@ class TestStripeNestedResourceGetRows:with pytest.raises(stripe_lib.InvalidRequestError):_run_nested_get_rows(nested_method)++ def test_parent_has_nested_skips_filtered_parents_without_calling(self):+ called_for: list[str] = []++ def nested_method(customer=None, params=None):+ called_for.append(customer)+ return _list_object([{"id": f"cbt_{customer}", "amount": 100}])++ # Only customers with a non-zero balance should trigger the nested call.+ rows = _run_nested_get_rows(+ nested_method,+ parent_objects=[+ {"id": "cus_zero", "balance": 0},+ {"id": "cus_credit", "balance": -500},+ {"id": "cus_owed", "balance": 1500},+ ],+ parent_has_nested=stripe_module._customer_might_have_balance_transactions,+ )++ # cus_zero is skipped entirely — no API call, no rows.+ assert called_for == ["cus_credit", "cus_owed"]+ assert {row["customer"] for row in rows} == {"cus_credit", "cus_owed"}+++class TestCustomerMightHaveBalanceTransactions:+ @pytest.mark.parametrize(+ "customer,expected",+ [+ ({"balance": 0}, False),+ ({"balance": -500}, True),+ ({"balance": 1500}, True),+ # Missing balance is an unexpected payload shape — fetch rather than silently drop data.+ ({}, True),+ ({"balance": None}, True),+ ],+ )+ def test_predicate(self, customer, expected):+ assert stripe_module._customer_might_have_balance_transactions(customer) is expected+++class TestWebhookEventMapping:+ def test_customer_balance_transaction_has_no_webhook_event(self):+ # Customer balance transactions have no Stripe webhook event, so the resource must not be in+ # the event map — otherwise we'd subscribe the source webhook to unrelated events.+ assert CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME not in RESOURCE_TO_STRIPE_WEBHOOK_EVENT++ def test_no_billing_events_subscribed(self):+ # The removed "billing" mapping was the only thing pulling in billing.* events (credit+ # grants, meters, alerts) — none of which can populate any table we sync.+ assert not any(e.startswith("billing.") or e.startswith("billing_") for e in _all_known_webhook_events())++ def test_payment_method_events_still_subscribed(self):+ # CustomerPaymentMethod keeps its mapping, so payment_method.* events stay subscribed.+ assert RESOURCE_TO_STRIPE_WEBHOOK_EVENT[CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME] == "payment_method"+ assert any(e.startswith("payment_method.") for e in _all_known_webhook_events())