Idempotent Multi-Tenant Webhook Fan-Out and Stopping FAMILY_SHARED Double-Counting in Catch
Inside Catch's Cloudflare Workers backend and SwiftUI client fixes for 1.1.0: notificationUUID + push_state delivery idempotency, D1 64 KB / 100-bind guards, excluding FAMILY_SHARED from revenue, 12-hour CONSUMPTION_REQUEST cleanup, and a macOS NavigationLink layout loop.
Catch runs its backend on Cloudflare Workers, D1, and KV, paired with a single-target SwiftUI app across iOS, iPadOS, and macOS. While wrapping up 1.1.0 fixes alongside App Store review, we uncovered several sharp bugs across webhook delivery, revenue math, D1 limits, and SwiftUI window focus.
Multi-Tenant Fan-Out Idempotency and D1 Hard Limits
A single Catch workspace can hold multiple team members, each owning up to 10 devices with independent quiet hours, sandbox toggles, per-app mutes, and chime.caf sound preferences. Because Apple retries failed webhooks for up to six-plus days (forcing MIN_RETENTION_DAYS = 7), worker/src/hook.js enforces idempotency at three layers:
- Atomic insert + daily cap:
payload.notificationUUIDserves as the primary key alongsideDAILY_EVENT_CAP = 1000inside oneINSERT OR IGNORE INTO events ... SELECT ... WHERE (SELECT COUNT(*) ... ) < ?statement so concurrent bursts cannot overshoot quota. - Per-device delivery ledger: Events start with
push_state = 'pending'. InsidefanOut(),hook.jsqueriesevent_deliveriesfirst, skips(user_id, token)pairs already delivered, pushes via APNs only to remaining devices, and records completions withenv.DB.batch. - Deliberate status codes:
push_stateflips to'sent'only when zero retryable failures remain; transient APNs errors return500, failedforward_urldeliveries (10_000 mstimeout,redirect: 'manual'so a307cannot loop back to/hook/<token>) return503, and unknown tokens orVerifyErrorsignatures return200(logging invalid payloads to a 7-day, 50-row-per-workspacedead_letterstable).
Two Cloudflare D1 limits also required explicit guards. readLimited() caps incoming /hook bodies at MAX_BODY_BYTES = 64 * 1024 (real V2 three-part JWS payloads run ~20–30 KB), returning 413 without writing dead_letters so one account cannot fill D1 with multi-megabyte junk. And because D1 caps SQL statements at 100 bound parameters, fanOut() chunks devices queries into batches of 90 user IDs.
Why a ¥68 Family Purchase Counted as ¥136
We initially assumed FAMILY_SHARED notifications carried a 0 price. Inspecting real payloads proved otherwise: Apple sends the family member’s FAMILY_SHARED notification with the full original item price, not zero.
For a ¥68 one-time purchase, the buyer receives a notification for ¥68, and each family member receives a second notification also carrying ¥68 (and every family subscription renewal repeats the pattern). Counting both doubled a ¥68 sale to ¥136 and rang the cash-register chime twice.
We fixed both sides together:
hook.jsskipsevent.ownership_type === "FAMILY_SHARED"during push fan-out and markspush_state = 'skipped'.worker/src/stats.jsfiltersMONEY_SCOPEwithAND ownership_type IS NOT 'FAMILY_SHARED'and blocks it inisIncomeEvent(). Because stats aggregate at query time, historical totals updated immediately, whileby_typestill surfaces afamily_sharedcount soStatsView.swiftcan note “Family Shared: N”,EventDetailView.swiftdims the price with an explanation, and CSV exports include anownershipcolumn.eventPrice()also handlesREFUND_PRORATEDusingrevocationPercentage(100000 = 100%), andREFUND_REVERSEDlooks up the priorREFUNDamount rather than blindly crediting the full item price.
Purging 12-Hour CONSUMPTION_REQUEST IDs via Hourly Cron
Catch deliberately discards customer identifiers (appAccountToken and originalTransactionId are never stored). The sole exception is CONSUMPTION_REQUEST, where Apple’s PUT /inApps/v2/transactions/consumption/{transactionId} endpoint requires transactionId within a 12-hour response window.
hook.js inserts transaction_id into consumption_requests only if event.ts + 12 * 3600 > now. In worker/src/index.js, an hourly cron (0 * * * *) deletes expired rows (deadline < now) independently of the daily retention cleanup, and listEvents applies AND c.deadline > ? on its LEFT JOIN so expired IDs stop serving immediately even between cron ticks.
Three SwiftUI Client Bugs Caught While Recording the Demo
Recording the 1.1.0 (8) iPad and Mac walkthrough exposed three subtle client bugs:
- macOS layout infinite loop (
NSGenericException): Opening Send Consumption Info fromViews/EventDetailView.swiftand switching focus to another window crashed AppKit minutes later. Reading@Environment(\.dismiss)directly insideEventDetailView.bodyalongside aNavigationLinkcarrying anonSentclosure caused navigation updates to invalidatedismiss, recomputebody, re-register the closure-backedNavigationLink, and loop endlessly once unfocused. Moving the two filter buttons into a privateFilterShortcutssubview isolateddismissand stopped the loop. - Silent CSV failure on macOS:
Catch-macOS.entitlementswas missingcom.apple.security.files.user-selected.read-write, blocking the save panel entirely. 1e-16float residuals overflowingInt: InViews/StatsView.swift,DeltaLabelcomputed((current - prev) / abs(prev) * 100).rounded()and cast it toInt. Floating-point subtraction residuals like1e-16blew pastInt.maxand crashed. Snappingabs($0) < 0.005to0, clamping deltas to[-999_999, 999_999], and checkingprevious_completefromstats.jsfixed both the crash and misleading comparisons on truncated periods.
Comments