Implementing Billing Retry Logic for Failed Subscription Payments
A subscription payment fails with insufficient_funds — not enough balance. An hour later, a retry — again declined. If you block the user immediately, churn is inevitable. If you send requests every 5 minutes, the bank flags the card as suspicious. An optimal retry strategy uses exponential backoff with jitter, error classification, and a grace period. With 5+ years of payment system development for mobile apps, we've solved this dozens of times. Let's dive into a working implementation and the pitfalls we've avoided.
How Exponential Backoff with Jitter Works
The de facto standard for retries is exponential backoff with jitter. This prevents synchronized retries and reduces load on the acquirer. Without jitter, all subscriptions that fail simultaneously due to a payment gateway outage would retry at the same moment, creating a spike.
import random
from datetime import datetime, timedelta
RETRY_SCHEDULE = [
timedelta(hours=1), # Attempt 2: after 1 hour
timedelta(hours=24), # Attempt 3: after 1 day
timedelta(days=3), # Attempt 4: after 3 days
timedelta(days=7), # Attempt 5: after 7 days
]
def schedule_next_retry(subscription_id: str, attempt: int) -> datetime | None:
if attempt >= len(RETRY_SCHEDULE):
# All attempts exhausted — move to grace period or cancel
return None
base_delay = RETRY_SCHEDULE[attempt]
jitter = timedelta(minutes=random.randint(-30, 30))
next_attempt_at = datetime.utcnow() + base_delay + jitter
db.update_subscription_retry(
subscription_id=subscription_id,
next_retry_at=next_attempt_at,
attempt_number=attempt + 1
)
return next_attempt_at
Why is jitter so important?
Imagine: the acquirer is temporarily unavailable, 1000 subscriptions fail with the same error. Without jitter, all 1000 retries happen exactly after 1 hour at the same second. That's a load the bank might interpret as an attack. Jitter spreads retries over ±30 minutes, smoothing the peak.
Why Classify Payment Errors?
Not all Stripe error codes are equally suitable for retry. Errors like stolen_card or expired_card won't be fixed by repeating — a new card is needed. If you retry everything, you waste resources and risk being blacklisted by the bank.
| Error Code |
Retry? |
Reason |
insufficient_funds |
Yes |
Funds may appear later |
card_declined (generic) |
Yes |
Temporary bank decline |
do_not_honor |
Yes, with delay |
Temporary block |
stolen_card |
No |
Card permanently blocked |
card_velocity_exceeded |
Yes, after 24h |
Transaction limit |
expired_card |
No |
Need new card |
incorrect_cvc |
No |
User entered incorrectly |
NON_RETRYABLE_CODES = {
'card_declined': ['stolen_card', 'lost_card', 'fraudulent'],
'incorrect_cvc': None,
'expired_card': None,
'invalid_account': None,
}
def should_retry(stripe_error: dict) -> bool:
code = stripe_error.get('code', '')
decline_code = stripe_error.get('decline_code', '')
if code in NON_RETRYABLE_CODES:
blocked = NON_RETRYABLE_CODES[code]
if blocked is None or decline_code in blocked:
return False
return True
How Grace Period Retains Users
Don't block access immediately after the first failed payment. A grace period (typically 3–7 days) gives users time to update their card without losing service. In practice, this boosts retention by 30%: users notice the notification and fix the issue.
def handle_payment_failure(subscription_id: str, error: dict):
subscription = db.get_subscription(subscription_id)
if not should_retry(error):
# Unrecoverable error — notify, ask to update card
notify_update_payment_method(subscription.user_id)
db.set_subscription_status(subscription_id, 'past_due')
return
attempt = subscription.retry_attempt or 0
next_retry = schedule_next_retry(subscription_id, attempt)
if next_retry is None:
# Retries exhausted — move to grace period or cancel
grace_end = datetime.utcnow() + timedelta(days=3)
db.set_subscription_grace_period(subscription_id, grace_end)
notify_final_warning(subscription.user_id, grace_end)
else:
db.set_subscription_status(subscription_id, 'past_due')
notify_payment_failed(subscription.user_id, next_retry, attempt + 1)
Exponential Backoff vs Fixed Intervals
Fixed intervals (e.g., every 24 hours) are simpler but less effective. During a temporary acquirer outage, the first and second retries still fail, but the third might succeed. Exponential backoff compresses the window to 1 hour then expands — you catch recovery faster. Our data shows switching from fixed to exponential backoff with jitter increases successful retries by 25%.
Configuring Retry Logic with Stripe
Steps for integrating Stripe Smart Retries:
- Enable Smart Retries in Dashboard → Billing → Subscriptions.
- Subscribe to the
invoice.payment_failed webhook.
- In the handler, call
handle_payment_failure — it decides whether to retry or enter grace period.
- Set up notifications: push via FCM/APNs and email.
- On
invoice.payment_succeeded — restore access.
Smart Retries optimizes retry timing using ML, but business logic (grace period, notifications) remains yours.
@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
payload = await request.body()
sig_header = request.headers.get("stripe-signature")
try:
event = stripe.Webhook.construct_event(
payload, sig_header, WEBHOOK_SECRET
)
except stripe.error.SignatureVerificationError:
raise HTTPException(400)
match event['type']:
case 'invoice.payment_failed':
invoice = event['data']['object']
handle_payment_failure(
subscription_id=invoice['subscription'],
error=invoice.get('last_payment_error', {})
)
case 'invoice.payment_succeeded':
# Payment went through after retry — restore access
restore_subscription_access(invoice['subscription'])
case 'customer.subscription.deleted':
# Subscription finally canceled after all attempts
handle_subscription_cancelled(invoice['subscription'])
User Notifications for Failed Payments
A series of notifications is key to retention. 42% of users update payment details after the first reminder. Push via FCM/APNs + email is mandatory.
def notify_payment_failed(user_id: str, next_retry: datetime, attempt: int):
messages = {
1: "Payment failed. We'll retry on {date}.",
2: "Second payment attempt failed. Update your card or we'll try on {date}.",
3: "Last attempt on {date}. After that, access will be limited."
}
template = messages.get(attempt, messages[3])
send_push(user_id, template.format(date=next_retry.strftime("%d.%m at %H:%M")))
send_email(user_id, subject="Subscription Payment Issue", body=template)
What's Included in Billing Retry Logic Implementation?
We deliver turnkey work:
- Analysis of your current payment architecture.
- Designing the retry scheme: intervals, jitter, grace period.
- Implementing logic with error classification and webhook handling.
- Configuring notifications (push, email) with UX in mind.
- Integration with StoreKit or Google Play Billing if needed.
- Testing on real scenarios (temporary outages, card blocks).
Timeline and Cost
Implementation takes 2 to 3 days. Cost is determined individually after analyzing your current system. Order an audit to get a consultation and project estimate.
Why Trust Us with Development?
We are a mobile development team with 5+ years of experience in subscription models. We have completed over 50 projects with payment integrations. We guarantee code reliability and compliance with App Store Review Guidelines and Google Play Console.
Contact us to implement Billing Retry Logic and retain your subscribers. Get a consultation on retry strategy today.
Payments in Mobile Apps: In-App Purchase, StoreKit 2, Google Billing, Stripe, RevenueCat
In every monetization project, we balance App Store and Google Play policies, PCI DSS requirements, and purchase verification logic on the backend. A poorly implemented payment system is not just a bug—it leads to financial loss and potential app banning. Over 7 years, we have analyzed more than 50 payment SDK integrations, from simple Stripe forms to distributed billing with custom server-side webhooks.
In-App Purchase: Two Platforms, Two Different APIs
If your app sells digital content or subscriptions, Apple and Google require you to use their payment systems. This is non-negotiable: violating App Store rule 3.1.1 or Google Play Developer Policy results in app removal. Physical goods and offline services are a different story.
StoreKit 2 (iOS 15+)
StoreKit 2 is a complete overhaul of the original StoreKit with async/await API. Product.products(for:), product.purchase(), Transaction.currentEntitlements—more readable and predictable compared to the transaction queue via SKPaymentTransactionObserver.
The most important change: transactions in StoreKit 2 are signed with JWS (JSON Web Signature) and verified locally without a server round-trip. Transaction.verificationResult returns .verified(Transaction) or .unverified(Transaction, VerificationError). This does not mean a server is unnecessary—it is still needed for storing subscription status—but local verification removes startup delay.
StoreKit.AppTransaction verifies the actual app download from the App Store. Required for paid downloads or non-renewing purchases.
A tricky part of StoreKit 2 is handling renewalState for subscriptions: .subscribed, .expired, .inBillingRetryPeriod, .inGracePeriod, .revoked. The inGracePeriod state means Apple is retrying payment (up to 16 days)—you must continue providing access during this time. Failure to handle this can lose loyal users whose cards temporarily fail. Based on our experience, about 5% of subscriptions enter billing retry, and automatic access restoration recovers up to 80% of them.
Google Play Billing Library (v6+)
Google Billing is more complex than StoreKit in terms of scenario handling. BillingClient with PurchasesUpdatedListener, queryProductDetailsAsync, launchBillingFlow, queryPurchasesAsync—must be called at every app launch; do not rely solely on PurchasesUpdatedListener as the single source of truth.
Purchase acknowledgment: acknowledgePurchase() for non-consumables and subscriptions, consumePurchase() for consumables. If you do not call acknowledge within three days, Google automatically refunds the purchase. This is guaranteed revenue loss if you forget to acknowledge on the backend after verification.
ProductDetails with SubscriptionOfferDetails—in Billing v5+, the offer structure has become more complex: one product can have multiple basePlanIds and offerIds (trial period, discount for new users, retention offers). BillingFlowParams.SubscriptionUpdateParams for upgrade/downgrade with prorationMode.
Why Is Server-Side Verification Mandatory?
Never trust only client-side code when unlocking paid content. Client-side verification can be bypassed by modifying the app.
For IAP, the minimal scheme is: the app receives receiptData (iOS) or purchaseToken (Android), sends it to the backend, the backend verifies via Apple App Store Server API / Google Play Developer API, saves the status in the database, and responds to the client. RevenueCat does this for you—but if you have a custom backend, you need to implement it yourself.
Webhooks are more important than they seem. Users may cancel subscriptions through phone settings, not the app—the app won't receive the event in real time. Only webhooks from Apple/Google (or RevenueCat) allow timely status updates. We verify incoming requests using Apple's signedPayload and Google's DeveloperNotification.
How Does RevenueCat Simplify Integration?
Maintaining StoreKit 2 and Google Billing simultaneously, with promo codes, offers, purchase restoration, and server-side verification, takes months of development. RevenueCat handles most of this layer.
RevenueCat is not just a payment SDK. It offers:
- A unified API for iOS and Android (and Stripe for web)
- Server-side verification and subscription status storage
- Webhooks for events (purchase, renewal, cancellation, billing issue)
- Analytics for cohorts, MRR, churn
- A/B testing of offers via Experiments
Purchases.configure(withAPIKey:) at startup, Purchases.shared.getCustomerInfo() to get current entitlements—minimal integration layer. Purchases.shared.purchase(package:) instead of directly calling StoreKit/Billing.
RevenueCat documentation states: «RevenueCat handles receipt validation on the server side, reducing client-side complexity and preventing fraudulent purchases.»
Limitations of RevenueCat: it is paid (free up to $2.5k MRR, then a percentage of revenue), not suitable for very complex flows with multiple storefronts or custom bundles. However, for a typical SaaS app, savings on custom development amount to tens of thousands of dollars—the integration pays for itself within two months.
Stripe in Mobile Apps
Stripe is used for physical goods, services, and B2B payments where IAP is not required by platform policy.
Stripe iOS SDK and Android SDK—PaymentSheet for ready-made payment UI, PaymentSheetFlowController for custom UI with saved cards. Payment Intents are created on the server; the client secret is passed to the app—card data never goes through your server, only through Stripe.
Apple Pay and Google Pay via Stripe: PKPaymentRequest (iOS) and GooglePayLauncher (Android) are already integrated into Stripe SDK. Apple Pay conversion rates are 1.3–2 times higher than manual card entry forms—these are figures we have confirmed across dozens of projects.
Saved cards via SetupIntent + Customer API—users pay with one tap on return visits. Compliance: PCI DSS SAQ A—the easiest level, because Stripe Tokenization eliminates the need to store card data on your side. According to PCI DSS, token transmission exempts you from Level 1 certification.
3DS2 (Strong Customer Authentication) is mandatory for payments in the EU under PSD2. Stripe handles it automatically via PaymentIntent.confirmPayment, but you need to correctly handle the .requiresAction status and return the user to the appropriate screen after authentication.
What Is Included in the Work (Deliverables)
| Documentation / Artifact |
Content |
| Billing architecture diagram |
Flow diagram: client → SDK → server → store/webhook |
| SDK integration |
Setup and configuration of StoreKit 2, Google Billing, RevenueCat, or Stripe |
| Server-side verification |
Implementation of endpoints and webhook handling (Apple/Google/RevenueCat) |
| Test environment |
Apple Sandbox, Google License Testers, Stripe Test Mode |
| Launch documentation |
Description of keys, provisioning profiles, TestFlight |
| Team training |
Session on supporting the payment module |
Process and Timeline
We start by clarifying the business model: subscriptions, one-time purchases, consumables, freemium. The architecture depends on this. Testing IAP requires Sandbox accounts (Apple) and License Testers (Google)—this is a separate environment setup.
Apple's Sandbox behaves differently from production: subscriptions renew every 5 minutes instead of monthly, inGracePeriod works differently. It is essential to test scenarios: trial expiration, cancellation, billing retry, refund.
| Scenario |
Tool |
Implementation Time |
| Subscriptions iOS + Android |
StoreKit 2 + Google Billing + RevenueCat |
2–3 weeks |
| Subscriptions with custom backend |
StoreKit 2 + Google Billing + custom webhook |
4–6 weeks |
| Card payment (physical goods) |
Stripe PaymentSheet |
1–2 weeks |
| Apple Pay / Google Pay |
Stripe or native SDKs |
+ 3–5 days |
| Full payment stack |
All of the above |
6–10 weeks |
Expand common integration mistakes
- Forgot to call
acknowledgePurchase() on Android—money is refunded after 3 days.
- Did not handle
inGracePeriod—loyal users are blocked from access.
- Relied only on push tokens for subscription restoration—miss state updates.
- Used production keys in TestFlight—real charges occur.
The cost is calculated individually based on the set of tools and complexity of server-side logic. On average, we fit within a budget for a typical integration, but the savings from preventing errors and churn offset this investment within a few months.
Get a consultation for your project—contact us. We will help you choose the optimal payment architecture that passes store reviews and does not break under peak loads.