Building an Idempotent Webhook Handler for App Store & Google Play
In mobile subscription systems, webhooks are the lifeblood of server-side state synchronization. When a user renews, cancels, refunds, or upgrades, Apple and Google dispatch webhooks to notify your server. However, HTTP delivery is inherently unreliable. Webhooks can arrive out of order, be retried multiple times, or fail completely due to temporary network issues.
The Risks of Naive Webhook Handlers
If your backend simply updates a database field (e.g., UPDATE users SET active = true) every time a webhook arrives, you will eventually corrupt your subscription state. Consider this scenario:
- A user cancels their subscription. Apple dispatches a
DID_CHANGE_RENEWAL_STATUSwebhook (Event A). - The network lags. In the meantime, the billing cycle finishes, and Apple dispatches a renewal event (Event B).
- Due to routing delays, Event B arrives at your server before Event A.
- Your database sets active to true (Event B), then sets it to false (Event A). The user is active in Apple's eyes, but your database says they are canceled.
Pillar 1: Database Idempotency Logs
Every webhook payload contains a unique identifier (Apple's notificationUUID or Google Play's messageId). Your server must track these IDs in an idempotency_keys table before processing. Here is the recommended schema:
CREATE TABLE processed_webhooks (
event_id VARCHAR(255) PRIMARY KEY,
provider VARCHAR(50) NOT NULL, -- 'apple' | 'google'
user_id UUID,
processed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
status VARCHAR(20) DEFAULT 'processing' -- 'processing' | 'completed' | 'failed'
);
Pillar 2: Distributed Locking & Concurrency
Using a distributed lock on the user's ID (e.g. lock:user_123) ensures that only one worker thread updates their subscription status at a time, avoiding race conditions. Below is a complete Node.js/TypeScript handler with concurrency guard and sequencing check:
import { Request, Response } from 'express';
import { db } from '../db';
import { redis } from '../redis';
export async function handleWebhook(req: Request, res: Response) {
const { eventId, userId, signedDate, eventType } = req.body;
const lockKey = `lock:webhook:user:${userId}`;
// 1. Guard against duplicate events
try {
await db.query(
'INSERT INTO processed_webhooks (event_id, provider, user_id) VALUES ($1, $2, $3)',
[eventId, 'apple', userId]
);
} catch (err) {
// Unique violation - already processed
return res.status(200).send('Duplicate notification ignored');
}
// 2. Acquire Redis distributed lock (timeout 5s)
const lockAcquired = await redis.set(lockKey, "locked", "NX", "PX", 5000);
if (!lockAcquired) {
// Release the event log for retry
await db.query('DELETE FROM processed_webhooks WHERE event_id = $1', [eventId]);
return res.status(429).send('Concurrency lock busy, retrying');
}
try {
await db.transaction(async (tx) => {
// 3. Verify event sequencing (timestamp comparison)
const { rows } = await tx.query(
'SELECT last_event_time FROM user_subscriptions WHERE user_id = $1 FOR UPDATE',
[userId]
);
const lastEventTime = rows[0]?.last_event_time ? new Date(rows[0].last_event_time).getTime() : 0;
const incomingEventTime = new Date(signedDate).getTime();
if (incomingEventTime <= lastEventTime) {
// Out-of-order/delayed event
await tx.query(
'UPDATE processed_webhooks SET status = $1 WHERE event_id = $2',
['ignored', eventId]
);
return;
}
// 4. Update subscription state
await tx.query(
`UPDATE user_subscriptions
SET status = $1, last_event_time = $2
WHERE user_id = $3`,
[eventType === 'SUBSCRIBED' ? 'active' : 'expired', signedDate, userId]
);
await tx.query(
'UPDATE processed_webhooks SET status = $1 WHERE event_id = $2',
['completed', eventId]
);
});
res.status(200).send('Success');
} catch (error) {
await db.query('UPDATE processed_webhooks SET status = $1 WHERE event_id = $2', ['failed', eventId]);
res.status(500).send('Transaction failed');
} finally {
await redis.del(lockKey);
}
}
Abstracting Webhook Complexity with BillDog
Building and maintaining a queue-backed, idempotent webhook infrastructure takes weeks of developer time. With BillDog, all webhook streams are normalized, sequenced, and retried at the SDK layer. Your server receives a single normalized state payload instead of two vendors' raw notification streams, which removes the ordering and replay handling described above from your codebase — it does not make delivery infallible, and you should still treat entitlement state as something to reconcile rather than assume.
Get the BillDog newsletter
Practical guides on subscription pricing, paywalls and app growth, about twice a month. No spam.
