Stop Your Agent From Replying Twice: Dedup Patterns
Ever watched an email agent reply to the same message twice? The recipient gets two near-identical responses seconds apart, screenshots them, and your carefully engineered assistant suddenly looks like a script with a stutter. Worse: under real load, this isn't a freak event. It's the default outcome if you haven't designed against it. The double-reply problem has three distinct causes, and each one needs its own fix. Let's walk through them. Why duplicates happen at all First cause: webhook redelivery . Nylas — like most webhook providers — guarantees at-least-once delivery. If your endpoint doesn't return a 200 fast enough, or a transient network blip eats the response, the same message.created notification shows up again. Process both, send two replies. Second: concurrent workers . Your handler probably runs on multiple instances — Lambda invocations, ECS tasks, worker processes. Two of them can pick up the same notification at nearly the same instant and both start generating a reply. Third: shared inboxes . Two agents (or an agent and a human) watching the same mailbox can both decide a message is theirs to answer. This one isn't a duplicate event at all — it's a coordination problem, and it's the hardest to patch at the application layer. Fix one: deduplicate deliveries Track which message IDs you've processed, and check before doing anything else: app . post ( " /webhooks/nylas " , async ( req , res ) => { res . status ( 200 ). end (); const event = req . body ; if ( event . type !== " message.created " ) return ; const messageId = event . data . object . id ; // Atomic check-and-set. If the key exists, bail. const alreadyProcessed = await db . processedMessages . setIfAbsent ( messageId , { receivedAt : Date . now (), }); if ( alreadyProcessed ) return ; await handleMessage ( event . data . object ); }); The check-and-set must be atomic. In Redis that's SET messageId 1 NX EX 86400 ; in Postgres it's INSERT ... ON CONFLICT DO NOTHING with a row-count check. G