Skip to content

Paddle Billing webhooks: subscription.created and subscription.updated - #6910

Open
aerosol wants to merge 23 commits into
masterfrom
paddle-billing-webhooks-handlers
Open

aerosol wants to merge 23 commits into
masterfrom
paddle-billing-webhooks-handlers

Conversation

@aerosol

@aerosol aerosol commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

This PR adds the webhook endpoint that creates and updates Paddle Billing subscriptions. Until now the app could read Billing subscriptions (#6879), but nothing wrote them.

Builds on #6909 (webhook signature verification) and #6898 (migration already applied). The diff will be smaller once #6909 is merged, plus majority of diffstat is tests, the logic is relatively small and self-contained. Reading commit by commit is the best way forward.

@RobertJoonas if you find yourself overwhelmed already, you can also start with these three diffs to get a grasp of core changes:


Deets:

POST /api/paddle-billing/webhook hits PaddleBillingController. The Classic endpoint is unchanged.

  1. WebhookSignature gains Plug capabilities. A failing request gets a 400 and an error log with the reason.
  2. The signature covers the exact bytes Paddle sent, so PlausibleWeb.RawBodyReader is introduced, keeping the raw body for this one route. Configured per plug docs recommendation. Other routes don't copy the body.
  3. The secret comes from PADDLE_BILLING_WEBHOOK_SECRET. With no secret configured, every request is rejected. .envrc.local is loaded in dev mode only to simplify sandbox experiments. The secret env var will be provisioned on prod in a follow-up.

The newly introduced controller only handlessubscription.created and subscription.updated. subscription.imported will be done in a follow-up.

Both events carry the whole subscription, so they share one code path.

  • Every event is stored in billing_subscription_events. A repeated event_id is a duplicate and results with HTTP 200.
  • Paddle doesn't guarantee ordering. An event older than the latest stored one for that subscription is recorded but not applied to subscription state.
  • created finds the team from custom_data (team_id, or user_id for a new personal team) and sets teams.billing_customer_id, which makes the all_subscriptions view return the appropriate Billing row. updated finds the subscription by ID. An unknown ID is an error.
  • A scheduled cancellation is stored as :deleted with next_bill_date set to when it takes effect, as with Classic. The cancellation email is sent once for :deleted (SubscriptionState.notify_cancellation/1 is now public).
  • billing_interval comes from the price's billing cycle. Only monthly and yearly are accepted.
  • The team state goes through the shared SubscriptionState.apply_subscription_state/1, so site locking, grace period, deletion schedules and enterprise API limits provide Classic parity.
  • A handled event that fails returns 400 so Paddle retries. An event we don't handle returns 200. Failed events keep their payload in billing_webhook_failures for inspection.

Additionally, the usage notification crashed when the pageview limit is :unlimited (for example, for a plan we can't resolve - easy to reach on dev env). Fixed, with a test.

@aerosol aerosol changed the title Paddle billing webhooks handlers Paddle Billing webhooks: subscription.created and subscription.updated Nov 23, 2026
@aerosol aerosol changed the title Paddle Billing webhooks: subscription.created and subscription.updated Paddle Billing webhooks: subscription.created and subscription.updated Nov 23, 2026
@aerosol
aerosol force-pushed the paddle-billing-webhooks-handlers branch from a60b927 to 0c08ac6 Compare November 23, 2026 07:22
@aerosol
aerosol force-pushed the paddle-billing-webhooks-handlers branch from 0c08ac6 to 78dffd9 Compare November 23, 2026 07:36
@aerosol
aerosol marked this pull request as ready for review November 23, 2026 07:39
@aerosol
aerosol requested a review from RobertJoonas November 23, 2026 07:39
Base automatically changed from paddle-webhook-signature to master November 24, 2026 09:29
…ooks-handlers

# Conflicts:
#	lib/plausible/billing/paddle_billing/webhook_signature.ex
@aerosol

aerosol commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Merged #6909 here, diff against master now

@RobertJoonas RobertJoonas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Neat! Thanks for a detailed description and a well built-up PR! Kudos for the test coverage too! 🙌

Left a few comments inline. Since I'm not fully sure whether any of them are blocking, I'll leave it up to you decide. Approved ✅

Comment thread config/runtime.exs Resolved

# Paddle doesn't guarantee delivery order. An event is stale when another event
# of the same subscription, with a later `occurred_at`, is already stored.
defp stale?(billing_subscription_id, event_id, occurred_at) do

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should also account for two different webhook events for the same subscription arriving very close to each other? I.e. we end up processing them at the same time, the first transaction isn't committed yet before the second one starts, neither stale?/3 call sees the other event and the older one can overwrite the newer state.

I'm not sure how likely that is to happen, but we might want to consider an advisory lock on the subscription ID.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking we could solve that with row-level locks and upserts, but it gets pretty complex pretty fast (if not impossible). Your idea about using advisory locks seems to be a better option. I'd even opt for creating a lock on team ID so that we can more straightforwardly resolve issues like two created events coming in for the same team but for 2 different subscriptions (highly unlikely, but still theoretically possible).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6abb68c - WYT?

@zoldar zoldar Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good start! I'd consider simplifying at least part of upserts into inserts/updates. Another thing would be detecting situations like attempting insertion of a new subscription with existing one active, for instance.

existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id)

case {kind, existing} do
{:updated, nil} -> {:error, :subscription_not_found}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The subscription.updated webhook returning 400 for this reason can keep Paddle retrying until exhaustion. I wonder if we should prevent that to avoid noise in the logs and webhook_failures? The following scenario is quite realistic I think:

  • A team schedules their subscription to be cancelled in 20 days
  • After 10 days, the team creates a new subscription which overwrites the existing one (only one billing subscription can exist at a time)
  • After 20 days, when a subscription.updated with status: canceled finally arrives, a subscription with this ID is not found
  • Paddle will keep retrying up to 60 times, during ~2 days

I understand we can't just return 200 for any unknown subscription because we still need to let Paddle retry when subscription.updated of a subscription that was just created, arrives before subscription.created. But we could perhaps use billing_subscription_events to tell these two cases apart? If there are existing events for this subscription ID, we know that it has been replaced by a new one. WDYT?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oof I think your comment uncovers that I had forgotten to implement "only one active subscription" can exist for Billing. IIRC we were planning for this with Adrian, let me get back to this

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm thinking something like: #6917 - \cc @zoldar when you're around

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have normalised billing_subscription_id (along with all the other fields) in SubscriptionEvent schema. We could fall back on looking up the most recent entry in the events table and treat that as a "stale" event insertion. However, we should still ensure it doesn't do something unexpected, like changing the canceled subscription back to active (unlikely, but still). Then it should legit crash.

IMHO it would be better to avoid relaxing the one-team-one-billing-subscription constraint, if possible.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, will do that

end

defp process(kind, %{"event_id" => event_id, "data" => %{} = data} = event) do
with :ok <- check_not_seen(event_id),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it would make sense to attempt inserting event "stub" first, basically with event_id only, to ensure any process running in parallel with the same event_id sees it? A failed insert (or rather upsert via on_conflict) at this stage would abort the transaction as a duplicate early as well. The stub could be updated in record_event.

end

defp find_existing(kind, billing_subscription_id) do
existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd consider setting a row-level lock via FOR UPDATE to avoid working with a stale subscription due to two different events being processed in parallel for the same subscription.

existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id)

case {kind, existing} do
{:updated, nil} -> {:error, :subscription_not_found}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have normalised billing_subscription_id (along with all the other fields) in SubscriptionEvent schema. We could fall back on looking up the most recent entry in the events table and treat that as a "stale" event insertion. However, we should still ensure it doesn't do something unexpected, like changing the canceled subscription back to active (unlikely, but still). Then it should legit crash.

IMHO it would be better to avoid relaxing the one-team-one-billing-subscription constraint, if possible.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants