Menu

Three ways this codebase refuses to do a thing twice, and the TTL is never the runtime
📰

Three ways this codebase refuses to do a thing twice, and the TTL is never the runtime

DEV Community: postgres·Daniel Pertu·1 day ago
#eJQ51yYH
#devtopostgresql#devto#dev#claim#three
Reading 0:00
15s threshold

Munchable has three kinds of work that must not happen twice: webhook deliveries, scheduled jobs, and a monthly settlement pass that touches subscriptions. All three are "exactly once" problems. None of them use the same mechanism, and the reason is that they fail differently.

The common mistake in all three, which I made in two of them, is the same: setting the guard's lifetime to how long the work takes.

1. Webhooks: a short claim, promoted on success

Stripe and Resend both retry on a non-2xx and both occasionally deliver a duplicate. The handlers have side effects, so each event id is claimed before anything happens:

const key = `webhook:${provider}:${eventId}` ; const claimed = await redis . set ( key , Date . now ( ) . toString ( ) , { nx : true , ex : ttlSeconds } ) ; if ( claimed === null ) return { isFirstDelivery : false , degraded : false } ;

Enter fullscreen mode

Exit fullscreen mode

SET NX plus a TTL, rather than a table, because the record only has to outlive the provider's retry window.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.